🪓 Split a string in Go

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

🖨️ Convert string to []byte or []byte to string in Go

Learn the difference between a string and a byte slice
introduction strings slice

🔟 Convert string to bool in Go

Learn how to parse a string as a bool
introduction strings bool

👯 Remove duplicate spaces from a string in Go

Learn how to remove all redundant whitespaces from a string
introduction strings regex