How to split a string into a slice in Go
Using strings.Split Function
Use the strings.Split
function to split a string into its comma separated values.
package main
import (
"fmt"
"strings"
)
func main() {
s := "Japan,Germany"
// func Split(s, sep string) []string
slice := strings.Split(s, ",")
fmt.Printf("%q\n", slice)
// sep is empty
slice = strings.Split(s, "")
fmt.Printf("%q\n", slice)
}
["Japan" "Germany"] ["J" "a" "p" "a" "n" "," "G" "e" "r" "m" "a" "n" "y"]
If s does not contain sep and sep is not empty, Split returns a slice of length 1 whose only element is s.
If sep is empty, Split splits after each UTF-8 sequence. If both s and sep are empty, Split returns an empty slice.
Using strings.Fields Function
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. For example,
package main
import (
"fmt"
"strings"
)
func main() {
s := "Japan Germany"
// var asciiSpace = [256]uint8{'\t': 1, '\n': 1, '\v': 1, '\f': 1, '\r': 1, ' ': 1}
// func Fields(s string) []string
slice := strings.Fields(s)
fmt.Printf("%q\n", slice)
}
["Japan" "Germany"]
Using the regexp Split Function
Split slices s into substrings separated by the expression and returns a slice of the substrings between those expression matches. The count determines the number of substrings to return. if n < 0, it returns all substrings. For example,
package main
import (
"fmt"
"regexp"
)
func main() {
s := "abaabaccad"
a := regexp.MustCompile(`a`)
// func (re *Regexp) Split(s string, n int) []string
fmt.Printf("%q\n", a.Split(s, -1))
fmt.Printf("%q\n", a.Split(s, 0))
fmt.Printf("%q\n", a.Split(s, 1))
}
["" "b" "" "b" "cc" "d"] [] ["abaabaccad"]
You can use regexp.Split
to split a string into a slice of strings with the regex pattern as the delimiter.
package main
import (
"fmt"
"regexp"
)
func main() {
s := "how789to1234split"
a := regexp.MustCompile(`[0-9]+`)
fmt.Printf("%q\n", a.Split(s, -1))
}
["how" "to" "split"]