How to iterate through each character of a string in Golang?

WBOY
Release: 2024-03-13 16:36:03
Original
346 people have browsed it

How to iterate through each character of a string in Golang?

How to iterate through each character of a string in Golang?

In Golang, strings are actually composed of bytes, and each character may be represented by multiple bytes. Therefore, to iterate over each character of a string, we need to first convert the string into a rune slice. rune is a data type in the Go language that is used to represent Unicode characters.

Next, I will introduce the method of string traversal using Go language and provide code examples.

First, we define a string containing Chinese characters:

package main

import (
    "fmt"
)

func main() {
    str := "你好,世界!"
    runes := []rune(str)

    for i := 0; i < len(runes); i++ {
        fmt.Printf("%c ", runes[i])
    }
}
Copy after login

In this code, we first convert the string "Hello, world!" into a rune slice. Then, we use a for loop to traverse the rune slice and output each character through the fmt.Printf("%c ", runes[i]) statement.

When we run this code, the output is:

你 好 , 世 界 !
Copy after login

With the above example, we successfully iterated through the string containing Chinese characters and output each character. In Golang, this method is a relatively simple and efficient way to traverse strings. I hope this article is helpful to you, thank you for reading!

The above is the detailed content of How to iterate through each character of a string in Golang?. 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
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!