Home  >  Article  >  Backend Development  >  How Do I Iterate Over Strings by Runes in Go?

How Do I Iterate Over Strings by Runes in Go?

Patricia Arquette
Patricia ArquetteOriginal
2024-11-27 15:34:111003browse

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)
}

This will print:

character 日 starts at byte position 0
character 本 starts at byte position 3
character 語 starts at byte position 6

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!

Statement:
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