DEV Community

Lane Wagner for Boot.dev

Posted on • Originally published at qvault.io on

Splitting a String into a Slice in Golang

#go

splitting a lemon

The post Splitting a String into a Slice in Golang first appeared on Qvault.

I can’t begin to tell you how often I split strings in Go. More often than not I’m just parsing a comma-separated list from an environment variable, and Go’s standard library gives us some great tools for that kind of manipulation.

Split by commas or other delimiters

strings.Split()

Go’s rich standard library makes it really easy to split a string. 99% of the time you need to split strings in Go, you’ll want the strings package’s strings.Split() function.

package main

import (
    "fmt"
    "strings"
)

func main() {
    fruitsString := "apple,banana,orange,pear"
    fruits := strings.Split(fruitsString, ",")
    fmt.Println(fruits)
    // prints ["apple", "banana", "orange", "pear"]
}

Enter fullscreen mode Exit fullscreen mode

strings.SplitN()

The strings.SplitN() function takes three arguments: the string to be split, a separator, and the number of resulting strings in the slice.

To be honest I don’t use this function very often, but it might be useful if you’re working on a large document and only care about the first few sentences or something along those lines.

package main

import (
    "fmt"
    "strings"
)

func main() {
    fruitsString := "apple.banana.orange.pear"
    fruits := strings.SplitN(fruitsString, ".", 3)
    fmt.Println(fruits)
    // prints ["apple", "banana", "orange.pear"]
}
Enter fullscreen mode Exit fullscreen mode

Split by delimiters and retain the delimiters

strings.SplitAfter()

Similar to Split(), SplitAfter() splits the original string but leaves the delimiters at the end of each substring.

package main

import (
    "fmt"
    "strings"
)

func main() {
    fruitsString := "apple.banana.orange.pear"
    fruits := strings.SplitAfter(fruitsString, ".")
    fmt.Println(fruits)
    // prints ["apple.", "banana.", "orange.", "pear"]
}
Enter fullscreen mode Exit fullscreen mode

strings.SplitAfterN()

SplitAfterN does the same thing as SplitAfter except it only splits the first N substrings. Everything else is retained in the final substring.

package main

import (
    "fmt"
    "strings"
)

func main() {
    fruitsString := "apple.banana.orange.pear"
    fruits := strings.SplitAfterN(fruitsString, ".", 2)
    fmt.Println(fruits)
    // prints ["apple.", "banana.orange.pear"]
}
Enter fullscreen mode Exit fullscreen mode

Split by whitespace and newlines

The strings package can do more than just separate a string based on a provided delimiter. The strings.Fields() function will split on all whitespace , and exclude it from the final result. This is useful if you don’t care about the kind of whitespace, for example, tabs, spaces, and newlines all count as whitespace.

package main

import (
    "fmt"
    "strings"
)

func main() {
    fmt.Printf("Fields are: %q", strings.Fields(`apple
     banana orange
     pear
     `))
    // prints ["apple", "banana", "orange", "pear"]
}
Enter fullscreen mode Exit fullscreen mode

Split using a regex

Regular expressions are a popular way to manipulate strings, and Go’s built-in regex engine can help us out. We actually don’t even need to use the strings package here, instead we’ll use the regexp package.

package main

import (
    "fmt"
    "regexp"
)

func main() {
    s := regexp.MustCompile("[0-9]").Split("apple1banana2orange3pear", -1)
    fmt.Println(s)
    // prints ["apple", "banana", "orange", "pear"]
}
Enter fullscreen mode Exit fullscreen mode

Gotcha – Strings in Go are special

Be aware when you’re working with a lot of strings that Go treats strings differently than other languages like Java, C, and Python. Strings in Go are read-only slices of bytes, and those bytes are arbitrary – they can be anything. Strings in Go are not required to hold Unicode text, UTF-8 text, or any other encoding format.

Thanks for reading, now take a course!

Interested in a high-paying job in tech? Land interviews and pass them with flying colors after taking my hands-on coding courses.

Start coding now

Questions?

Follow and hit me up on Twitter @q_vault if you have any questions or comments. If I’ve made a mistake in the article be sure to let me know so I can get it corrected!

Subscribe to my newsletter for more coding articles delivered straight to your inbox.

Top comments (0)