split a string into an array of words in go

To split a string into an array of words in Go, you can use the strings.Fields() function. This function splits a string into words (using white space characters as delimiters) and returns an array of strings.

Here's an example code that demonstrates how to use strings.Fields() function:

main.go
package main

import (
	"fmt"
	"strings"
)

func main() {
	str := "The quick brown fox jumped over the lazy dog"
	words := strings.Fields(str)
	fmt.Println(words)
}
165 chars
13 lines

Output:

main.go
[The quick brown fox jumped over the lazy dog]
47 chars
2 lines

In this example, we first declare a string variable str, which contains a sentence. We then pass this string to the strings.Fields() function, which splits the string into individual words and returns an array of strings. Finally, we print the array of words using the fmt.Println() function.

related categories

gistlibby LogSnag