Split a string on whitespace in Go?

ralfoide picture ralfoide · Dec 6, 2012 · Viewed 75.6k times · Source

Given an input string such as " word1 word2 word3 word4 ", what would be the best approach to split this as an array of strings in Go? Note that there can be any number of spaces or unicode-spacing characters between each word.

In Java I would just use someString.trim().split("\\s+").

(Note: possible duplicate Split string using regular expression in Go doesn't give any good quality answer. Please provide an actual example, not just a link to the regexp or strings packages reference.)

Answer

I Hate Lazy picture I Hate Lazy · Dec 6, 2012

The strings package has a Fields method.

someString := "one    two   three four "

words := strings.Fields(someString)

fmt.Println(words, len(words)) // [one two three four] 4

DEMO: http://play.golang.org/p/et97S90cIH

From the docs:

func Fields(s string) []string

Fields splits the string s around each instance of one or more consecutive white space characters, returning an array of substrings of s or an empty list if s contains only white space.