Home » Golang String Fields() Function

Golang String Fields() Function

Fields() function in the Golang strings package splits the string around each instance of one or more consecutive white space characters as defined by Unicode.IsSpace. It returns a slice of substrings of the given string. If the given string is an empty string, it will return an empty slice.

Fields() Syntax

The syntax for Fields() function is:

func Fields(s string) []string

Fields() Parameters:

The Fields() function take string as an argument

s1 is the string

Fields() Return Value

The strigs package Fields() function returns a string array.

Let’s understand the string package Fields() method with examples.

strings.Fields() function to split a string into a slice

The following go program splits a string into a slice using the strings.Fields() function.

package main

import (
	"fmt"
	"strings"
)

func main() {

	// Split a string into a slice
	fmt.Println(strings.Fields("Fields splits the string"))
}

The output of the string split into a slice using the Fields() in go are:

[Fields splits the string]

In the above program,

Fields() function splits the given string “Fields splits the string” into a slice removing white space characters and returning a string array.

Conclusion

I hope the above article on the Fields() method to splits the string into substring removing white space characters is helpful to you.

You can find more topics about the Golang tutorials on the GolangSpot Home page.

Leave a Comment