Go 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 mainimport ("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.
Contribute to Docs
- Learn more about how to get involved.
- Edit this page on GitHub to fix an error or make an improvement.
- Submit feedback to let us know how we can improve 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