Sobes.tech
Junior — Middle

How can you iterate through the characters of a string in code?

sobes.tech AI

Answer from AI

In Go, to iterate over the characters (runes) of a string sequentially, the for range loop is used. This is important because a string in Go is a sequence of bytes, and Unicode characters can occupy multiple bytes.

Example:

s := "Привет"
for i, r := range s {
    fmt.Printf("Character %c starts at byte %d\n", r, i)
}

Here, r is a rune (Unicode character), and i is the byte index where this character starts in the string.

This approach allows for correct processing of multilingual strings and characters that occupy more than one byte.