33

How do I convert strings in an array to integers in an array in go?

["1", "2", "3"]

to

[1, 2, 3]

I've searched for some solutions online but couldn't find it. I've tried to loop through the array and did strconv.ParseFloat(v, 64) where v is the value but it didn't work.

5 Answers 5

45

You will have to loop through the slice indeed. If the slice only contains integers, no need of ParseFloat, Atoi is sufficient.

import "fmt"
import "strconv"

func main() {
    var t = []string{"1", "2", "3"}
    var t2 = []int{}

    for _, i := range t {
        j, err := strconv.Atoi(i)
        if err != nil {
            panic(err)
        }
        t2 = append(t2, j)
    }
    fmt.Println(t2)
}

On Playground.

Sign up to request clarification or add additional context in comments.

Comments

11

For example,

package main

import (
    "fmt"
    "strconv"
)

func sliceAtoi(sa []string) ([]int, error) {
    si := make([]int, 0, len(sa))
    for _, a := range sa {
        i, err := strconv.Atoi(a)
        if err != nil {
            return si, err
        }
        si = append(si, i)
    }
    return si, nil
}

func main() {
    sa := []string{"1", "2", "3"}
    si, err := sliceAtoi(sa)
    if err != nil {
        fmt.Println(err)
        return
    }
    fmt.Printf("%q %v\n", sa, si)
}

Output:

["1" "2" "3"] [1 2 3]

Playground:

http://play.golang.org/p/QwNO8R_f90

Comments

6

This is an ancient question but all the answers ignore the fact that the input length is known in advance, so it can be improved by pre-allocating the destination slice:

package main

import "fmt"
import "strconv"

func main() {
    var t = []string{"1", "2", "3"}
    var t2 = make([]int, len(t))
    
    for idx, i := range t {
        j, err := strconv.Atoi(i)
        if err != nil {
            panic(err)
        }
        t2[idx] = j
    }
    fmt.Println(t2)
}

Playground: https://play.golang.org/p/LBKnVdi_1Xz

Comments

1

A slice is a descriptor of an array segment
It consists of
- a pointer to the array,
- the length of the segment, and
- its capacity (the maximum length of the segment)

Below, string Array/Slice is converted to int Array/Slice:

package main

import (
    "fmt"
    "log"
    "strconv"
    "strings"
)

func Slice_Atoi(strArr []string) ([]int, error) {
    // NOTE:  Read Arr as Slice as you like
    var str string                           // O
    var i int                                // O
    var err error                            // O

    iArr := make([]int, 0, len(strArr))
    for _, str = range strArr {
        i, err = strconv.Atoi(str)
        if err != nil {
            return nil, err                  // O
        }
        iArr = append(iArr, i)
    }
    return iArr, nil
}

func main() {
    strArr := []string{
        "0 0 24 3 15",
        "0 0 2 5 1 5 11 13",
    }

    for i := 0; i < len(strArr); i++ {
        iArr, err := Slice_Atoi(strings.Split(strArr[i], " "))
        if err != nil {
            log.Print("Slice_Atoi failed: ", err)
            return
        }
        fmt.Println(iArr)
    }
}

Output:

[0 0 24 3 15]
[0 0 2 5 1 5 11 13]

I used in a project, so did a small optimizations from other replies, marked as // O for above, also fixed a bit in readability for others

Best of luck

Comments

0

Here is another example how to do this:

var t = []string{"1", "2", "3"}
str := strings.Join(t, "")
if _, err := strconv.Atoi(str); err != nil {
    // do stuff, in case str can not be converted to an int
}
var slice []int // empty slice
for _, digit := range str {
    slice = append(slice, int(digit)-int('0')) // build up slice
}

I like this because you have to check only once if each digit inside of t can be converted to an int. Is it more efficient? I don`t know.

Why do you need the int('0')? Because int() will convert the character to the corresponding ASCII code (ascii table here). For 0 that would be 48. So you will have to substract 48 from whatever your digit corresponds to in "ascii decimal".

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.