How do I convert string of int slice to int slice?

你说的曾经没有我的故事 提交于 2020-06-09 07:08:49

问题


Example input: (type: string)

"[156, 100, 713]"

Example conversion: (type: slice of int)

[156, 100, 713]

回答1:


In addition to mhutter's answer, also note that your input string looks like a JSON array (maybe it is from a JSON text?).

If you treat it like that, you may unmarshal its content into an []int slice. This won't be faster that directly parsing the numbers from it (as the encoding/json package uses reflection), but it is certainly simpler:

s := "[156, 100, 713]"

var is []int
if err := json.Unmarshal([]byte(s), &is); err != nil {
    panic(err)
}

fmt.Println(is)
fmt.Printf("%#v", is)

Output (try it on the Go Playground):

[156 100 713]
[]int{156, 100, 713}



回答2:


Given a string

in := "[156, 100, 713]"

First, let's get rid of the square brackets:

trimmed := strings.Trim(in, "[]")
//=> "156, 100, 713"

Next, split the string into a slice of strings:

strings := strings.Split(trimmed, ", ")
//=> []string{"156", "100", "713"}

Now we can convert the strings to ints

ints := make([]int, len(strings))

for i, s := range strings {
    ints[i], _ = strconv.Atoi(s)
}

fmt.Printf("%#v\n", ints)
//=> []int{156, 100, 713}

For more Information see the go docs: https://devdocs.io/go/strings/index



来源:https://stackoverflow.com/questions/39013158/how-do-i-convert-string-of-int-slice-to-int-slice

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!