HiveBrain v1.2.0
Get Started
← Back to all entries
patterngoCritical

Split a string on whitespace in Go?

Submitted by: @import:stackoverflow-api··
0
Viewed 0 times
stringwhitespacesplit

Problem

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.)

Solution

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:

Fields splits the string s around each instance of one or more consecutive white space characters, as defined by unicode.IsSpace, returning a slice of substrings of s or an empty slice if s contains only white space.

Code Snippets

someString := "one    two   three four "

words := strings.Fields(someString)

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

Context

Stack Overflow Q#13737745, score: 419

Revisions (0)

No revisions yet.