strings.Split Examples (SplitAfter, SplitN)
This page was last reviewed on Dec 1, 2022.
Dot Net Perls
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.
Argument 1 This is the data string we want to separate apart—it should contain a delimiter char or pattern.
Argument 2 This is the delimiter 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
Read file lines. 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.
Part 1 We open the file.txt text file on the local disk. Please adjust this file name to one that is valid on your system.
Part 2 We use a 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 circle
red,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.
So 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.
Here We split on the characters X and Y. The string is split into a slice of three substrings.
Note The second argument to 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
Individual chars. 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.
Detail The third argument to 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
Fields, FieldsFunc. Consider also the Fields() method. It treats a sequence of delimiter chars as a single delimiter (unlike Split). We can use it with spaces or another character.
Join. Take a string and split it apart. We can join it together again with join(), and this is often done in Go. We invoke strings.Join as part of the strings package.
With Split, SplitN, SplitAfter and SplitAfterN we separate strings. These methods return a string slice—this is idiomatic Go. Join meanwhile combines strings.
Dot Net Perls is a collection of tested code examples. Pages are continually updated to stay current, with code correctness a top priority.
Sam Allen is passionate about computer languages. In the past, his work has been recommended by Apple and Microsoft and he has studied computers at a selective university in the United States.
No updates found for this page.
© 2007-2024 Sam Allen.