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:
The above is the detailed content of How Do I Iterate Over Strings by Runes in Go?. For more information, please follow other related articles on the PHP Chinese website!