How Do I Iterate Over Strings by Runes in Go?

Patricia Arquette
Release: 2024-11-27 15:34:11
Original
1004 people have browsed it

How Do I Iterate Over Strings by Runes in Go?

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

This will print:

character 日 starts at byte position 0
character 本 starts at byte position 3
character 語 starts at byte position 6
Copy after login

The range syntax does the following:

  • Iterates from 0 to the length of the string
  • For each position, extracts the rune at that position using the UTF-8 encoding

The above is the detailed content of How Do I 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