How to split a string into a slice

yourbasic.org/golang

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.

White space

Use the strings.Fields function to split a string into substrings removing white space.

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

General case

In more complicated situations, the Regexp.Split function might do the trick.

Further reading

This Regexp in-depth tutorial is a gentle introduction to the Go regexp package with cheat sheet and plenty of examples.

Share this page: