TheDeveloperBlog.com


Golang Split Examples

Split. Often strings are concatenated together, with many parts in a single string. They are separated by delimiter chars. We can split these into slices of many strings.


With the strings package, we gain access to the Split and Join methods. Split has many variants, and selecting one can be confusing. These methods are powerful.


To begin, we use the Split method—please note how we import the "strings" package at the top. Split returns a slice of strings. Split receives two arguments.

First argument: This is the data string we want to separate apart—it should contain a delimiter char or pattern.

Second argument: This is the delimiter char or string. The delimiter can be any length.

Based on:

Golang 1.4

Golang program that uses strings, Split method

package main

import (
    "fmt"
    "strings"
)

func main() {
    data := "cat,bird,dog"

    // Split on comma.
    result := strings.Split(data, ",")

    // Display all elements.
    for i := range result {
	fmt.Println(result[i])
    }
    // Length is 3.
    fmt.Println(len(result))
}

Output

cat
bird
dog
3

Join. This method combines a slice of strings into a single string. We pass it the slice as the first argument. The delimiter to be inserted is the second.

Example: Here we create an empty string slice and then append three strings. We join those strings together with ellipses.

Golang program that uses Join

package main

import (
    "fmt"
    "strings"
)

func main() {
    // Create a slice and append three strings to it.
    values := []string{}
    values = append(values, "cat")
    values = append(values, "dog")
    values = append(values, "bird")

    // Join three strings into one.
    result := strings.Join(values, "...")
    fmt.Println(result)
}

Output

cat...dog...bird

Fields. A field is separated by one or more space characters. The Fields() method in the strings package separates these into an array. It splits on groups of spaces.

Golang program that uses Fields method

package main

import (
    "fmt"
    "strings"
)

func main() {
    value := "Cat Dog    Bird  Fish"
    result := strings.Fields(value)

    // Display all fields, first field and count.
    fmt.Println(result)
    fmt.Println(result[0])
    fmt.Println(len(result))
}

Output

[Cat Dog Bird Fish]
Cat
4

FieldsFunc. This method allows us to specify the field separator as a func. The fund must receive a rune and return a bool (whether the char is a separator).

Golang program that uses FieldsFunc

package main

import (
    "fmt"
    "strings"
)

func main() {
    // Return true if comma or colon char.
    f := func(c rune) bool {
	return c == ',' || c == ':'
    }
    // Separate into fields with func.
    fields := strings.FieldsFunc("cat,dog:bird", f)
    fmt.Println(fields)
}

Output

[cat dog bird]

Read file lines. This example reads in a text file that has multiple lines. It then splits each line as we encounter it. The bufio package is used to provide a Scan() method.

Open: We open the file.txt text file on the local disk. Please adjust this file name to one that is valid on your system.

Scan: We use a for-loop and call Scan() and Text() to get the current line. We then split each line on its commas.

Golang program that splits all lines in file

package main

import (
    "bufio"
    "fmt"
    "os"
    "strings"
)

func main() {
    // Open the file and scan it.
    f, _ := os.Open("C:\\programs\\file.txt")
    scanner := bufio.NewScanner(f)

    for scanner.Scan() {
	line := scanner.Text()

	// Split the line on commas.
	parts := strings.Split(line, ",")

	// Loop over the parts from the string.
	for i := range parts {
	    fmt.Println(parts[i])
	}
	// Write a newline.
	fmt.Println()
    }
}

Output

red
yellow
green
blue

square
circle

Contents of file.txt

red,yellow,green,blue
square,circle

With Split, SplitN, SplitAfter and SplitAfterN we separate strings. These methods return a string slice—this is idiomatic Go. Join meanwhile combines strings.