Golang fmt.Sscanf()函数及示例
在Go语言中,fmt包实现了类似于C语言的printf()和scanf()函数的格式化I/O。fmt包中的fmt.Sscanf()函数扫描指定的字符串,并根据格式将连续的空格分隔值存储为连续的参数。此外,此函数是在fmt包中定义的。在这里,您需要导入“fmt”包以使用这些函数。
用法:
func Sscanf(str string, format string, a ...interface{}) (n int, err error)
参数:
此函数接收三个参数,如下所示:
- str string: 此参数包含要扫描的指定文本。
- format string: 此参数是所指定字符串中每个元素的不同类型格式。
- a …interface{}: 此参数接收字符串的每个元素。
返回: 返回成功解析的项目数。
示例1:
// Golang program to illustrate the usage of
// fmt.Sscanf() function
// Including the main package
package main
// Importing fmt
import (
"fmt"
)
// Calling main
func main() {
// Declaring two variables
var name string
var alphabet_count int
// Calling the Sscanf() function which
// returns the number of elements
// successfully parsed and error if
// it persists
n, err := fmt.Sscanf("GFG is having 3 alphabets.",
"%s is having %d alphabets.", &name;, &alphabet;_count)
// Below statements get
// executed if there is any error
if err != nil {
panic(err)
}
// Printing the number of
// elements and each elements also
fmt.Printf("%d: %s, %d\n", n, name, alphabet_count)
}
输出:
2: GFG, 3
示例2:
// Golang program to illustrate the usage of
// fmt.Sscanf() function
// Including the main package
package main
// Importing fmt
import (
"fmt"
)
// Calling main
func main() {
// Declaring some variables
var name string
var alphabet_count int
var float_value float32
var boolean_value bool
// Calling the Sscanf() function which
// returns the number of elements
// successfully parsed and error if
// it persists
n, err := fmt.Sscanf("GeeksforGeeks 13 6.7 true",
"%s %d %g %t", &name;, &alphabet;_count,
&float;_value, &boolean;_value)
// Below statements get executed
// if there is any error
if err != nil {
panic(err)
}
// Printing the number of elements
// and each elements also
fmt.Printf("%d: %s, %d, %g, %t", n, name,
alphabet_count, float_value, boolean_value)
}
输出:
4: GeeksforGeeks, 13, 6.7, true
极客教程