🪓 Split a string in Go

April 19, 2021
introduction strings

To split a string in Golang, you can use any of the four functions available in the strings package:

See the examples to compare these four ways to split a string:

package main

import (
    "fmt"
    "strings"
)

func main() {
    str := "strawberry, blueberry, raspberry"

    fmt.Println("strings.Split():")
    for _, s := range strings.Split(str, ", ") {
        fmt.Printf("- %s\n", s)
    }
    fmt.Printf("\nstrings.SplitN()\n")
    for _, s := range strings.SplitN(str, ", ", 2) {
        fmt.Printf("- %s\n", s)
    }

    fmt.Printf("\nstrings.SplitAfter()\n")
    for _, s := range strings.SplitAfter(str, ", ") {
        fmt.Printf("- %s\n", s)
    }
    fmt.Printf("\nstrings.SplitAfterN()\n")
    for _, s := range strings.SplitAfterN(str, ", ", 2) {
        fmt.Printf("- %s\n", s)
    }
}

Output:

strings.Split():
- strawberry
- blueberry
- raspberry

strings.SplitN()
- strawberry
- blueberry, raspberry

strings.SplitAfter()
- strawberry, 
- blueberry, 
- raspberry

strings.SplitAfterN()
- strawberry, 
- blueberry, raspberry

✒️ Write to a CSV file in Go

Learn how to write data to a CSV or TSV file
introduction file

🙌 Case-insensitive string comparison in Go

Learn how to compare strings in a case-insensitive manner
introduction strings

🏁 Check if a string starts with a substring in Go

Learn how to use strings.HasPrefix() function
introduction strings