golang fmt.Ssanf详解

Golang fmt.Sscanf()实例讲解
时间:2022-04-07
本文章向大家介绍Golang fmt.Sscanf()实例讲解,主要分析其语法、参数、返回值和注意事项,并结合实例形式分析了其使用技巧,希望通过本文能帮助到大家理解应用这部分内容。
在Go语言中,fmt软件包使用与C的printf()和scanf()函数相似的函数来实现格式化的I /O。 Go语言中的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

posted @ 2022-11-03 21:50  技术颜良  阅读(407)  评论(0编辑  收藏  举报