"If a worker wants to do his job well, he must first sharpen his tools." - Confucius, "The Analects of Confucius. Lu Linggong"
Front page > Programming > How Do I Iterate Over Strings by Runes in Go?

How Do I Iterate Over Strings by Runes in Go?

Posted on 2025-03-24
Browse:428

How Do I Iterate Over Strings by Runes in Go?

Iterating Over Strings by Runes in Go

In Go, when attempting to iterate over a string using indices, you may encounter an issue where str[i] returns a byte instead of a rune. This is because strings in Go are sequences of bytes, not runes.

To iterate over strings by runes, use the range keyword. For example:

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

This will print:

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

The range syntax does the following:

  • Iterates from 0 to the length of the string
  • For each position, extracts the rune at that position using the UTF-8 encoding
Latest tutorial More>

Disclaimer: All resources provided are partly from the Internet. If there is any infringement of your copyright or other rights and interests, please explain the detailed reasons and provide proof of copyright or rights and interests and then send it to the email: [email protected] We will handle it for you as soon as possible.

Copyright© 2022 湘ICP备2022001581号-3