Open In App

strings.Fields() Function in Golang With Examples

strings.Fields() Function in Golang is used to splits the given string around each instance of one or more consecutive white space characters, as defined by unicode.IsSpace, returning a slice of substrings of str or an empty slice if str contains only white space.

Syntax:



func Fields(str string) []string

Returns: A slice of substrings of str or an empty slice if str contains only white space.

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

Output:

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

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

Output:

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

Article Tags :