String traversal method: 1. Use the "for range" statement to traverse, the syntax is "for key, value := range str {...}"; 2. Use the Map() function of the strings package to traverse , the syntax is "trings.Map(func(rune), original string)", where the parameter "func(rune)" is a callback function used to process each character in the string.
The operating environment of this tutorial: Windows 7 system, GO version 1.18, Dell G3 computer.
Methods for traversing strings in go language
Method 1: Use the for range statement
## The #for range structure is a unique iteration structure of the Go language. It is very useful in many situations. for range can traverse arrays, slices, strings, maps and channels. The syntax of for range is similar to that in other languages. The foreach statement, the general form is:for key, val := range coll { ... }
for pos, char := range str { ... }
package main import ( "fmt" ) func main() { var str = "hello 你好" for key, value := range str { fmt.Printf("key:%d value:0x%x\n", key, value) } }
Method 2: Use the strings.Map() function
In the development process, many times we need to correspond to each character in a string For processing, in the Go language, the strings.Map() function is provided to implement such a function.func Map(mapping func(rune) rune, s string) string
Description | |
---|---|
Processing function for each character in the string. | |
Original string. |
package main import ( "fmt" "strings" ) func strEncry(r rune)rune{ return r+1 } func main() { //使用 strings.Map() 函数,实现将一个字符串中的每一个字符都后移一位 strHaiCoder := "HaiCoder" mapStr := strings.Map(strEncry, strHaiCoder) fmt.Println("mapStr =", mapStr) }
Analysis:
The above is the detailed content of How to traverse strings in go language. For more information, please follow other related articles on the PHP Chinese website!