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.
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.
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
", sa, si)
}
Output:
["1" "2" "3"] [1 2 3]
Playground:
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
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".