3 ways to split a string into a slice

yourbasic.org/golang

Split on comma

Use the strings.Split function to split a string into its comma separated values.

s := strings.Split("a,b,c", ",")
fmt.Println(s)
// Output: [a b c]

To include the separators, use strings.SplitAfter. To split only the first n values, use strings.SplitN and strings.SplitAfterN.

Split by whitespace and newline

Use the strings.Fields function to split a string into substrings removing any space characters, including newlines.

s := strings.Fields(" a \t b \n")
fmt.Println(s)
// Output: [a b]

Split on any character or delimeter

In more complicated situations, the regexp Split method might do the trick.

It splits a string into substrings separated by a regular expression. The method takes an integer argument n; if n >= 0, it returns at most n substrings.

a := regexp.MustCompile(`a`)              // Delimiter: a single`a`
fmt.Printf("%q\n", a.Split("banana", -1)) // ["b" "n" "n" ""]
fmt.Printf("%q\n", a.Split("banana", 0))  // [] (nil slice)
fmt.Printf("%q\n", a.Split("banana", 1))  // ["banana"]
fmt.Printf("%q\n", a.Split("banana", 2))  // ["b" "nana"]

zp := regexp.MustCompile(`z+`)            // Delimiter: one or more `z`:s
fmt.Printf("%q\n", zp.Split("pizza", -1)) // ["pi" "a"]
fmt.Printf("%q\n", zp.Split("pizza", 0))  // [] (nil slice)
fmt.Printf("%q\n", zp.Split("pizza", 1))  // ["pizza"]
fmt.Printf("%q\n", zp.Split("pizza", 2))  // ["pi" "a"]

Further reading

See this Regexp tutorial and cheat sheet for a gentle introduction to the Go regexp package with plenty of examples.

Share this page: