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


Golang strings.Fields()用法及代碼示例

strings.Fields() Golang中的函數用於在unicode.IsSpace定義的一個或多個連續空白字符的每個實例周圍拆分給定的字符串,返回str的子字符串切片或如果str僅包含空白的空白切片。

用法:
func Fields(str string) []string

返回值:str的子字符串切片或如果str僅包含空格的空白切片。

範例1:

// Golang program to illustrate the 
// strings.Fields() Function 
package main 
    
import ( 
    "fmt"
    "strings"
) 
    
func main() {    
               
    // String s is split on the basis of white spaces 
    // and store in a string array 
    s:= "GeeksforGeeks is a computer science portal !"
    v:= strings.Fields(s) 
    fmt.Println(v)      
       
    // Another example by passing the string as argument 
    // directly to the Fields() function 
    v = strings.Fields("I am a software developer, I love coding") 
    fmt.Println(v) 
}

輸出:

[GeeksforGeeks is a computer science portal !]
[I am a software developer, I love coding]

範例2:

// Golang program to illustrate the 
// strings.Fields() Function 
package main 
  
import ( 
    "fmt"
    "strings"
) 
  
func main() { 
  
    // Fields function also splits the string 
    // on the basis of white spaces and tabs 
    s:= strings.Fields(" I \t love \n to \n code \n all \t day.") 
    fmt.Println(s) 
  
    // Splits into 5 words which have 
    // newline character in between 
    s = strings.Fields("I\nam\nlearning\nGo\nlanguage") 
    fmt.Println(s) 
}

輸出:

[I love to code all day.]
[I am learning Go language]



相關用法


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