Go: How to split a string into a slice
Split
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
.
Fields
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]
For more complex cases, use regular expressions.
Comments
Be the first to comment!