Go – Split String

To split a string in Go programming, call strings.Split() function and provide the string and delimiter values to the function.

In this tutorial, we will learn how to split a string in Go using Split() function with examples.

Syntax

The syntax of strings.Split() function is

strings.Split(str, sep_string)

where

  1. strings is the package.
  2. Split is the function name.
  3. str is the input string.
  4. sep_string is the delimiter or separator.

strings.Split() function returns string array []string.

ADVERTISEMENT

Examples

In the following program, we take a string str and split it with hyphen - as delimiter.

example.go

package main

import (
	"fmt"
	"strings"
)

func main() {
	var str = "a-b-c"
	var delimiter = "-"
	var parts = strings.Split(str, delimiter)
	fmt.Println(parts)
}

Output

[a b c]

In the following program, we will take a string containing values separated by comma. And we will split this string with comma , as delimiter.

example.go

package main

import (
	"fmt"
	"strings"
)

func main() {
	var str = "a,b,c"
	var delimiter = ","
	var parts = strings.Split(str, delimiter)
	fmt.Println(parts)
}

Output

[a b c]

Conclusion

In this Golang Tutorial, we learned how to split a string in Go using strings.Split() function.