Welcome To Golang By Example

Split a string in Go(Golang)

Table of Contents

Overview

In Golang string are UTF-8 encoded. strings package of GO provides a Split method that can be used to split a string by a separator.

Below is the signature of the function:

func Split(s, sep string) []string

As you can notice the return value of the Split function is a slice of string. Let’s notice some points about this method

Code

package main

import (
    "fmt"
    "strings"
)

func main() {
    //Case 1 s contains sep. Will output slice of length 3
    res := strings.Split("ab$cd$ef", "$")
    fmt.Println(res)

    //Case 2 s doesn't contain sep. Will output slice of length 1
    res = strings.Split("ab$cd$ef", "-")
    fmt.Println(res)

    //Case 3 sep is empty. Will output slice of length 8
    res = strings.Split("ab$cd$ef", "")
    fmt.Println(res)

    //Case 4 both s and sep are empty. Will output empty slice
    res = strings.Split("", "")
    fmt.Println(res)
}

Output:

[ab cd ef]
[ab$cd$ef]
[a b $ c d $ e f]
[]