问题
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