📜  Golang 中的字符串.Fields()函数示例

📅  最后修改于: 2021-10-25 02:23:40             🧑  作者: Mango

字符串.Fields() Golang函数用于将给定的字符串围绕一个或多个连续空白字符的每个实例拆分,如unicode.IsSpace定义的那样,如果 str 仅包含白色,则返回 str 的子字符串切片或空切片空间。

示例 1:

func Fields(str string) []string

输出:

// 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)
}

示例 2:

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

输出:

// 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)
}