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.
In order to convert string to integer type in Golang, you can use the following methods. You can use the strconv package's Atoi() function to convert the string into an integer value. Atoi stands for ASCII to integer. The Atoi() function returns two values: the result of the conversion, and the error (if any).
Go language provides inbuilt support to implement conversions to and from string representations of basic data types by strconv Package. This package provides an Atoi() function which is equivalent to ParseInt(str string, base int, bitSize int) is used to convert string type into int type.
Golang strconv. The strconv package's ParseInt() function converts the given string s to an integer value i in the provided base (0, 2 to 36) and bit size (0 to 64). Note: To convert as a positive or negative integer, the given string must begin with a leading sign, such as + or - .
You can convert numbers to strings by using the strconv. Itoa method from the strconv package in the Go standard libary. If you pass either a number or a variable into the parentheses of the method, that numeric value will be converted into a string value.
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\n", sa, si)
}
Output:
["1" "2" "3"] [1 2 3]
Playground:
http://play.golang.org/p/QwNO8R_f90
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
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With