stringloopsgorune

How can I iterate over a string by runes in Go?


I wanted to this:

for i := 0; i < len(str); i++ {
    dosomethingwithrune(str[i]) // takes a rune
}

But it turns out that str[i] has type byte (uint8) rather than rune.

How can I iterate over the string by runes rather than bytes?


Solution

  • See this example from Effective Go :

    for pos, char := range "日本語" {
        fmt.Printf("character %c starts at byte position %d\n", char, pos)
    }
    

    This prints :

    character 日 starts at byte position 0
    character 本 starts at byte position 3
    character 語 starts at byte position 6
    

    For strings, the range does more work for you, breaking out individual Unicode code points by parsing the UTF-8.