Iterating Over Strings By Runes in Go
Iterating over strings character by character can be useful in various programming scenarios. However, in Go, accessing characters directly using str[i] results in accessing bytes rather than Unicode runes. Therefore, it's necessary to explore alternative methods for iterating over strings by runes.
To iterate over a string by runes, you can utilize the range keyword. As demonstrated in the example from Effective Go:
for pos, char := range "日本語" { fmt.Printf("character %c starts at byte position %d\n", char, pos) }
This loop will iterate over the Unicode code points in the string, printing the character and its corresponding byte position.
The key takeaway is that the range keyword intelligently parses the UTF-8 string, breaking it down into individual Unicode code points, resulting in more efficient and convenient iteration.
위 내용은 Go에서 룬으로 문자열을 반복하는 방법은 무엇입니까?의 상세 내용입니다. 자세한 내용은 PHP 중국어 웹사이트의 기타 관련 기사를 참조하세요!