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

How to Iterate Over a String by Runes in Go?

Susan Sarandon
Release: 2024-11-13 11:19:02
Original
839 people have browsed it

How to Iterate Over a String by Runes in Go?

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

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

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

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!

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