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:

filter_none

edit
close

play_arrow

link
brightness_4
code

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

chevron_right


Output:

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

Example 2:

filter_none

edit
close

play_arrow

link
brightness_4
code

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

chevron_right


Output:

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



My Personal Notes arrow_drop_up

Check out this Author's contributed articles.

If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.


Article Tags :

1


Please write to us at contribute@geeksforgeeks.org to report any issue with the above content.