Iterating Over a String by Runes in Go
In Go, you may encounter a situation where you want to iterate over a string by its individual runes, or Unicode code points. You may be tempted to use a traditional for loop with the index i to access each character:
for i := 0; i < len(str); i++ { dosomethingwithrune(str[i]) // takes a rune }
However, this approach won't work correctly because str[i] returns a byte (uint8) instead of a rune. To iterate over the string by runes, you need to use the range syntax:
for pos, char := range "日本語" { fmt.Printf("character %c starts at byte position %d\n", char, pos) }
This code will print the following output:
character 日 starts at byte position 0 character 本 starts at byte position 3 character 語 starts at byte position 6
As the documentation for Effective Go explains, the range syntax "does more work for you, breaking out individual Unicode code points by parsing the UTF-8." This allows you to work with runes directly, making it easier to perform Unicode-related operations on your strings.
The above is the detailed content of How to Iterate Over a String by Runes in Go?. For more information, please follow other related articles on the PHP Chinese website!