May 152019


How to split a string into slice in Golang

  • 15 May 2019
  • ADM


How to split a string into slice in Golang - images/logos/golang.jpg


Here are two examples of how to split a string into slice using Golang. For a simple split by a singular character you can use Split() method from strings package. For more complex rules the regexp.Split() method can be used.

If you need help how to install Golang check the references links.


Simple split

package main

import (

func main() {
	fmt.Println("Simple string split Golang Example")
	str := "test,string,split"
	s := strings.Split(str, ",")
	fmt.Println(str, " ==> ", s)

Regexp split

The method takes also an integer argument n; if n >= 0, it returns at most n substrings. if n == -1 will returns all unlimited number of subtrings

package main

import (

func main() {
	fmt.Println("Regexp string split Golang Example")
	str := "test,string,split"
	delimiter1 := regexp.MustCompile(`,`) // Delimiter: a single`,` character

	fmt.Println("Single character delimiter")
	fmt.Printf("1. %q\n", delimiter1.Split(str, -1))
	fmt.Printf("2. %q\n", delimiter1.Split(str, 0))
	fmt.Printf("3. %q\n", delimiter1.Split(str, 1))
	fmt.Printf("4. %q\n", delimiter1.Split(str, 2))

	fmt.Println("Multiple character delimiter")
	str = "test,string,,split"
	delimiter2 := regexp.MustCompile(`,+`) // Delimiter: one or more `,` characters
	fmt.Printf("5. %q\n", delimiter2.Split(str, -1))
	fmt.Printf("6. %q\n", delimiter2.Split(str, 0))
	fmt.Printf("7. %q\n", delimiter2.Split(str, 1))
	fmt.Printf("8. %q\n", delimiter2.Split(str, 2))	


To compile the code navigate to the file location and run the following command.

$ go build stringSplit.go

Then depending on if you are on Linux or Windows the binary file is created.

To run the application execute the command.


$ ./stringSplit


c:\Users\adm\go\tutorials> stringSplit.exe

If you want to compile and run the application in one single step run the following command:

go run stringSplit.go


Simple split

Simple string split Golang Example

test,string,split  ==>  [test string split]

Regexp split

Regexp string split Golang Example

Single character delimiter

1. ["test" "string" "split"]
2. []
3. ["test,string,split"]
4. ["test" "string,split"]

Multiple character delimiter

5. ["test" "string" "split"]
6. []
7. ["test,string,,split"]
8. ["test" "string,,split"]