What is the Fields() function in Go?

The strings package is a Go standard library package that contains functions to manipulate UTF-8 encoded strings.

The Fields() method

The package provides the Fields() method, which can be used to split a string around one or more instances of consecutive whitespace characters.

The whitespace characters are as defined by unicode.IsSpace().

Syntax


func Fields(s string) []string

Arguments

This method takes the string s as input.

Returns

  • It returns a slice of substrings of input string s, after splitting the string on whitespace.

  • For an input string that contains only whitespace characters, it returns an empty slice.

Splitting a string on whitespaces using the Fields() function

Code

First, we imported the fmt and strings package to our program in the code below:

package main
import (
"fmt"
"strings"
)
func main() {
str1 := " educative io ui is awesome "
str2 := "\t New york is\t\t calling "
fmt.Println("String : ", str1)
fmt.Printf("Calling Fields(): %q", strings.Fields(str1))
fmt.Println("\nString : ", str2)
fmt.Printf("Calling Fields(): %q", strings.Fields(str2))
}

Explanation

  • After importing fmt, we call the Fields() method with " educative io ui is awesome " as the input string. This returns a slice of strings ["educative" "io" "ui" "is" "awesome"] after splitting the input string on the whitespaces.

  • We call the Fields() method with " New york is calling " as the input string, which also includes the tab characters. This returns a slice of strings ["New" "york" "is" "calling"] after splitting the input string on the whitespaces.

  • We show the output of all these operations using the Println() method of the fmt package.

Output

This program shows below output and exits:

String :    educative io ui is awesome  
Calling Fields():  ["educative" "io" "ui" "is" "awesome"]
String :  	  New york is		 calling 
Calling Fields():  ["New" "york" "is" "calling"]

Free Resources