Splitting a String into a Slice in Golang
Tags: go
Published: 2021-04-19 14:03:45

---
title: Splitting a String into a Slice in Golang
published: true
date: 2021-04-15 12:20:22 UTC
tags: Golang
canonical_url: https://qvault.io/golang/split-strings-golang/
---

 ![splitting a lemon](https://qvault.io/wp-content/uploads/2021/04/splitting-a-lemon.jpeg "splitting a lemon")

The post [Splitting a String into a Slice in Golang](https://qvault.io/golang/split-strings-golang/) first appeared on [Qvault](https://qvault.io).

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](#delimiters)
  - [strings.Split](#strings-split)

  - [strings.SplitN](#strings-split-n)
- [Split by delimiters and retain the delimiters](#retain-delimiters)
  - [strings.SplitAfter](https://qvault.io/wp-admin/post.php?post=220051&action=edit#strings-split-after)

  - [strings.SplitAfterN](https://qvault.io/wp-admin/post.php?post=220051&action=edit#strings-split-after-n)
- [Split by whitespace and newlines](#whitespace)
- [Split using a regex](#regex)

## 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](https://golang.org/pkg/strings) package’s [strings.Split() function](https://golang.org/pkg/strings/#Split).

```go
package main

import (
    "fmt"
    "strings"
)

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

```

### 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.

```go
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"]
}
```

## 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.

```go
package main

import (
    "fmt"
    "strings"
)

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

### 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.

```go
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"]
}
```

## 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](https://golang.org/pkg/strings/#Fields) 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.

```go
package main

import (
    "fmt"
    "strings"
)

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

## 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](https://golang.org/pkg/regexp/).

```go
package main

import (
    "fmt"
    "regexp"
)

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

## Gotcha – Strings in Go are special

Be aware when you’re working with a lot of strings that [Go treats strings differently](https://blog.golang.org/strings) 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](https://qvault.io)

### Questions?

Follow and hit me up on Twitter [@q\_vault](https://twitter.com/q_vault) if you have any questions or comments. If I’ve made a mistake in the article be sure to [let me know](https://qvault.io/contact/) so I can get it corrected!

[Subscribe](https://mailchi.mp/5c7f5c281bbe/qvault-newsletter-subscribe) to my newsletter for more coding articles delivered straight to your inbox.