当前位置: 首页>>代码示例 >>用法及示例精选 >>正文


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。非经特殊声明,原始代码版权归原作者所有,本译文未经允许或授权,请勿转载或复制。