Fields()
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.
Looking to contribute?
- 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.