Home > Backend Development > Golang > How to Iterate Over Strings by Runes in Go?

How to Iterate Over Strings by Runes in Go?

Linda Hamilton
Release: 2024-11-14 21:20:02
Original
645 people have browsed it

How to Iterate Over Strings by Runes in Go?

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)
}
Copy after login

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.

The above is the detailed content of How to Iterate Over Strings by Runes in Go?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template