Split
Often strings are concatenated together, with many parts in a single string
. They are separated by delimiter chars. We can split these into slices of many strings.
With the strings package, we gain access to the Split
and Join
methods. Split
has many variants, and selecting one can be confusing. These methods are powerful.
To begin, we use the Split
method—please note how we import the "strings" package at the top. Split
returns a slice of strings. Split
receives 2 arguments.
string
we want to separate apart—it should contain a delimiter char
or pattern.char
or string
. The delimiter can be any length.package main import ( "fmt" "strings" ) func main() { data := "cat,bird,dog" // Split on comma. result := strings.Split(data, ",") // Display all elements. for i := range result { fmt.Println(result[i]) } // Length is 3. fmt.Println(len(result)) }cat bird dog 3
This example reads in a text file that has multiple lines. It then splits each line as we encounter it. The bufio package is used to provide a Scan()
method.
for
-loop and call Scan()
and Text()
to get the current line. Inside the loop, we split each line on its commas.package main import ( "bufio" "fmt" "os" "strings" ) func main() { // Part 1: open the file and scan it. f, _ := os.Open("C:\\programs\\file.txt") scanner := bufio.NewScanner(f) // Part 2: call Scan in a for-loop. for scanner.Scan() { line := scanner.Text() // Split the line on commas. parts := strings.Split(line, ",") // Loop over the parts from the string. for i := range parts { fmt.Println(parts[i]) } // Write a newline. fmt.Println() } }red yellow green blue square circlered,yellow,green,blue square,circle
SplitAfter
This method splits on a zero-character position that comes after the specified delimiter. All the delimiters are retained in the resulting substrings.
SplitAfter
separates at the point directly after the delimiter you specify. This can be useful if you want to keep delimiters.package main import ( "fmt" "strings" ) func main() { value := "one.two.three" // Split after the period. result := strings.SplitAfter(value, ".") // Display our results. for i := range(result) { fmt.Println(result[i]) } }one. two. three
Regexp
Split
A regular expression can be used to split a string
. We first compile a regexp
with MustCompile
. The regexp
uses a pattern that matches delimiters in a string
.
string
is split into a slice of three substrings.regexp
Split
is the "limit" on the number of substrings to split. A negative number indicates no limit.package main import ( "fmt" "regexp" ) func main() { value := "catXdogYbird" // First compile the delimiter expression. re := regexp.MustCompile(`[XY]`) // Split based on pattern. // ... Second argument means "no limit." result := re.Split(value, -1) for i := range(result) { fmt.Println(result[i]) } }cat dog bird
With SplitAfter
, we can extract the individual characters of a string
into a string
slice. We split after an empty string
.
package main import ( "fmt" "strings" ) func main() { value := "bird" // Split after an empty string to get all letters. result := strings.SplitAfter(value, "") for i := range(result) { // Get letter and display it. letter := result[i] fmt.Println(letter) } }b i r d
SplitN
This method receives an argument that indicates the max number of strings to return. So if you pass 3, only the first two delimiters will be split upon.
SplitN
is the max number of strings in the resulting slice. The final string
may have remaining delimiters.package main import ( "fmt" "strings" ) func main() { value := "12|34|56|78" // Split into three parts. // ... The last separator is not split. result := strings.SplitN(value, "|", 3) for v := range(result) { fmt.Println(result[v]) } }12 34 56|78
With Split
, SplitN
, SplitAfter
and SplitAfterN
we separate strings. These methods return a string
slice—this is idiomatic Go. Join
meanwhile combines strings.