Convert string to []int?

Is there any way to convert string like 1 2 3 4 5 to []int?

You have to do it by splitting the text by the separator (space) and then convert digit by digit.

package main

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

func splitToInts(str string) ([]int, error) {
	ints := []int{}

	for _, s := range strings.Split(str, " ") {
		i, err := strconv.Atoi(s)
		if err != nil {
			return []int{}, err
		}

		ints = append(ints, i)
	}

	return ints, nil
}

func main() {
	ints, err := splitToInts("1 2 3 4 5")
	fmt.Printf("%v, %w\n", ints, err)
}

Yes. I would:

  • Split the string into its “fields,” as Go calls them, with the strings.Fields function.
  • Then use strconv.Atoi to convert each string field into an integer (assuming the integers are base10 and can fit into an int):

https://play.golang.org/p/5eIdBwvbKjn

2 Likes