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
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.
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.
Note 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
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 pages with code examples, which are updated to stay current. Programming is an art, and it can be learned from examples.
Donate to this site to help offset the costs of running the server. Sites like this will cease to exist if there is no financial support for them.
Sam Allen is passionate about computer languages, and he maintains 100% of the material available on this website. He hopes it makes the world a nicer place.
This page was last updated on Jan 30, 2025 (simplify).