Search code examples
arraysstringintdigits

Convert string to array of single digit integers in Go


Spent several hours trying to find a solution to the 'simple' problem of converting a string of digits to an array of single digit integers in Go. Tried many different approaches, but always ran into a problem. Here is the last one tried. It builds, but gives index out of range at runtime, on the line indicated. There will probably be a few AHs that will mark me down for asking stupid questions, but I couldn't find a solution in the first 50 results of multiple Google searches. So come on dude, mark me down, you're the man. To the other 99%: Thanks for your patience and help.

package main
import (
    "fmt"
    "strconv"
    "strings"
    )
func main() {
    s := "876567747896354336739443262"
    var dstr []string = strings.SplitAfterN(s,"",len(s))
    var dint []int
    for i := 0; i < len(s); i++ {
        dint[i], _ = strconv.Atoi(dstr[i]) //index out of range at runtime
        fmt.Printf("dstr[%v] is: %s\n", i, dstr[i])
        fmt.Printf("dint[%v] is: %v\n", i, dint[i])
    }
}

Solution

  • Here is the answer. Morphiax showed me the error in my ways. Thanks dude, appreciated. It turns out that this is wrong: var dint []int . I should have given the size when creating the array, when not initializing it: var dint [27]int . Here's full code again:

    package main
    import (
        "fmt"
        "strconv"
        "strings"
        )
    func main() {
        s := "876567747896354336739443262"
        var dstr []string = strings.SplitAfterN(s,"",len(s))
        var dint [27]int
        for i := 0; i < len(s); i++ {
            dint[i], _ = strconv.Atoi(dstr[i]) 
            fmt.Printf("dstr[%v] is: %s\n", i, dstr[i])
            fmt.Printf("dint[%v] is: %v\n", i, dint[i])
        }
    }