Home > Article > Backend Development > How to traverse strings in go language
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 { ... }It should be noted that val is always a copy of the value of the corresponding index in the collection, so it generally only has a read-only nature, and any modifications made to it will not Will affect the original values in the collection. A string is a collection of Unicode-encoded characters (or runes), so it can also be used to iterate strings:
for pos, char := range str { ... }Each rune character and index have a one-to-one correspondence in the for range loop , which can automatically identify Unicode-encoded characters according to UTF-8 rules. The following code shows how to traverse a string:
package main import ( "fmt" ) func main() { var str = "hello 你好" for key, value := range str { fmt.Printf("key:%d value:0x%x\n", key, value) } }The code output is as follows: The variable value in the code, the actual The type is rune type, and printing it in hexadecimal is the character encoding.
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!