将字符串数组转换为字符串数组。

huangapple go评论88阅读模式
英文:

convert string of array to array of string

问题

我有一个原始字符串,它由字符串数组组成,就像下面定义的那样:

"['a','b','c']"

我想将其转换为正确的字符串数组,如下所示:

["a","b","c"]

我正在尝试在Go语言中实现这个功能,但是我没有成功。在Go语言中如何实现这个功能呢?

英文:

I have a raw string which is formed from array of strings like the one defined below

"['a','b','c']"

which i want to convert to proper array of string as below

["a","b","c"]

I am trying this on golang. However, i didn't succeed in getting this done. How this can be accomplished in go

答案1

得分: 2

var s = "['a','b','c']"
ss := strings.Split(strings.Trim(s, "[]"), ",")
a := make([]string, len(ss))
for i := range ss {
    a[i] = strings.Trim(ss[i], "'")
}
out, err := json.Marshal(a)
if err != nil {
    panic(err)
}
fmt.Println(string(out))
// 输出: ["a","b","c"]

https://go.dev/play/p/kQ0Up06K9zz

英文:
var s = "['a','b','c']"
ss := strings.Split(strings.Trim(s, "[]"), ",")
a := make([]string, len(ss))
for i := range ss {
	a[i] = strings.Trim(ss[i], "'")
}
out, err := json.Marshal(a)
if err != nil {
	panic(err)
}
fmt.Println(string(out))
// output: ["a","b","c"]

https://go.dev/play/p/kQ0Up06K9zz

huangapple
  • 本文由 发表于 2022年9月6日 00:31:57
  • 转载请务必保留本文链接:https://go.coder-hub.com/73612334.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定