Go Fields()

Sumit_27's avatar
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.

  • Looking for an introduction to the theory behind programming? Master Python while learning data structures, algorithms, and more!
    • Includes 6 Courses
    • With Professional Certification
    • Beginner Friendly.
      75 hours
  • Learn how to use Go (Golang), an open-source programming language supported by Google!
    • Beginner Friendly.
      6 hours

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.

Code
Output

All contributors

Contribute to Docs

Learn Go on Codecademy

  • Looking for an introduction to the theory behind programming? Master Python while learning data structures, algorithms, and more!
    • Includes 6 Courses
    • With Professional Certification
    • Beginner Friendly.
      75 hours
  • Learn how to use Go (Golang), an open-source programming language supported by Google!
    • Beginner Friendly.
      6 hours