Fields()

Published Jul 11, 2023
Contribute to Docs

The Fields() function in Go is used to split a string into substrings based on whitespace and return a slice of the substrings. It removes any leading or trailing whitespace and treats consecutive whitespace characters as a single separator.

Syntax

strings.Fields(str)

Where str is the original string.

Example

The following example demonstrates the use of the strings.Fields() function.

package main
import (
"fmt"
"strings"
)
func main() {
str := "Hello World Golang"
fields := strings.Fields(str)
fmt.Println(fields)
}

The output will be:

[Hello World Golang]

Codebyte Example

The following example is runnable and uses the strings.Fields() function to split the string str. Then, each substring is printed with its respective index.

us
Visit us
code
Hide code
Code
Output
Hide output
Hide output
Loading...

All contributors

Looking to contribute?

Learn Go on Codecademy