當前位置: 首頁>>編程示例 >>用法及示例精選 >>正文


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



相關用法


注:本文由純淨天空篩選整理自Kanchan_Ray大神的英文原創作品 fmt.Sscanf() Function in Golang With Examples。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。