Christoper
Christoper

Reputation: 173

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

Example input: (type: string)

"[156, 100, 713]"

Example conversion: (type: slice of int)

[156, 100, 713]

Upvotes: 1

Views: 16739

Answers (2)

icza
icza

Reputation: 417602

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}

Upvotes: 7

mhutter
mhutter

Reputation: 2916

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

Upvotes: 9

Related Questions