英文:
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"]
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论