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:
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