Use the fmt.Sscanf function to read formatted data from a string and assign it to multiple variables
In the Go language, the fmt.Sscanf function can help us follow the specified format from a string Read the data and assign the read data to the corresponding variables. This provides great convenience for processing string data. This article will introduce how to use the fmt.Sscanf function and provide some sample code to help readers better understand.
First, let’s take a look at the basic usage of the fmt.Sscanf function. The definition of this function is as follows:
func Sscanf(str string, format string, a ...interface{}) (n int, err error)
In this function, str is the string to be parsed, format is the specified format, and a is the variable to be passed in. This function returns the number of parameters n successfully parsed and the error err during the parsing process.
Now suppose we have the following string: "Tom 20 180.12", from which we want to extract the name, age and height, and assign them to the corresponding variables respectively. The code is as follows:
package main import ( "fmt" ) func main() { str := "Tom 20 180.12" var name string var age int var height float64 n, err := fmt.Sscanf(str, "%s %d %f", &name, &age, &height) if err != nil { fmt.Printf("解析错误:%v ", err) } fmt.Printf("成功解析的参数数目:%d ", n) fmt.Printf("姓名:%s ", name) fmt.Printf("年龄:%d ", age) fmt.Printf("身高:%.2f ", height) }
The running results are as follows:
成功解析的参数数目:3 姓名:Tom 年龄:20 身高:180.12
In the code, we read the first string through the specified format string "%s %d %f" name variable, read the second integer into the age variable, and read the third floating point number into the height variable. Through the fmt.Printf function, we can print out the corresponding results.
If we want to extract more complex data, such as dates, etc., we can use some special characters. The following are some commonly used format characters:
Code example:
package main import ( "fmt" ) func main() { str := "2022-06-30" var year, month, day int n, err := fmt.Sscanf(str, "%d-%d-%d", &year, &month, &day) if err != nil { fmt.Printf("解析错误:%v ", err) } fmt.Printf("成功解析的参数数目:%d ", n) fmt.Printf("年:%d ", year) fmt.Printf("月:%d ", month) fmt.Printf("日:%d ", day) }
The running result is as follows:
成功解析的参数数目:3 年:2022 月:6 日:30
By using the fmt.Sscanf function, we can easily read from the string Take formatted data and assign it to multiple variables. Such a feature is very useful for working with string data and avoids the hassle of manually parsing strings. At the same time, using the specified format control string, we can also extract the required data more flexibly. I hope the sample code in this article can help readers better understand and use this function.
The above is the detailed content of Use the fmt.Sscanf function to read formatted data from a string and assign it to multiple variables. For more information, please follow other related articles on the PHP Chinese website!