Home > Backend Development > Golang > How can I iterate over a string by runes in Go?

How can I iterate over a string by runes in Go?

DDD
Release: 2024-11-16 03:56:03
Original
944 people have browsed it

How can I iterate over a string by runes in Go?

Iterating Over Strings by Runes in Go

When working with strings in Go, it's often necessary to iterate over the individual characters or runes that make up the string. While it may seem straightforward to use the built-in []byte type, this approach only considers the bytes that represent the runes, not the runes themselves.

To effectively iterate over a string by runes, you can utilize the range syntax, which provides a convenient way to loop over the Unicode code points of a string. This method automatically parses the string's UTF-8 encoding, allowing you to access the runes directly.

Here's an example:

for pos, char := range "日本語" {
    fmt.Printf("character %c starts at byte position %d\n", char, pos)
}
Copy after login

This code 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 iterates over the Unicode code points of the string, providing access to both the code point itself (represented by char) and its starting byte position in the string (represented by pos). This allows for flexible processing of the runes within a string.

The above is the detailed content of How can I 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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template