B
B
beduin012016-04-11 22:29:26
go
beduin01, 2016-04-11 22:29:26

How to translate a string into an array of numbers in Go?

Here I have a string "1,3,5,6,8". How can I get an array of numbers from it?

Answer the question

In order to leave comments, you need to log in

3 answer(s)
F
fastpars, 2016-04-11
@fastpars

1. get []string
https://golang.org/pkg/strings/#Split
2. create []int with length like []string.
There are 2 "correct" options:
If we want to fill through append, then we use:
Or if we want to fill through an index, then we do this:
https://golang.org/ref/spec#Slice_types
https://golang.org/ref/ spec#Length_and_capacity
3. iterate for range over []string and fill in []int.
https://golang.org/ref/spec#For_statements
https://golang.org/pkg/strconv/#Atoi
Don't forget to handle errors.

A
Alexander Aksentiev, 2016-04-11
@Sanasol

https://golang.org/pkg/strings/#Split

A
Alexander Pavlyuk, 2016-04-11
@pav5000

https://play.golang.org/p/gGU5-rsySS

package main

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

func main() {
  str := "1,3,5,6,8,42"

  strs := strings.Split(str, ",")
  var ints []int
  for _, s := range strs {
    num, err := strconv.Atoi(s)
    if err == nil {
      ints = append(ints, num)
    }
  }

  fmt.Println(ints)
}

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question