In this blog, we will learn how to split string by delimiter in Golang using Split, SplitN and SplitAfter Functions present in the strings package.
Learn how to compare strings in Golang.
Golang Split String to Array
func Split(s, t string) []string
The Split function takes a string to split and a separator string to split on and does as many splits as possible.
Split on Space
fmt.Println(strings.Split("My Name is Divyanshu Shekhar.", " "))
Split on Comma
fmt.Println(strings.Split("Learn Split Function, in Golang Strings package", ","))
Split on Dot
fmt.Println(strings.Split("Go.exe", "."))
[My Name is Divyanshu Shekhar.]
[Learn Split Function in Golang Strings package]
[Go exe]
Function returns an array of string that got split by the delimiter.
Split String Using SplitN
func SplitN(s, t string, n int) []string
If you want to limit the number of splits we can use the strings.SplitN()
function
instead.
Example of SplitN function:
fmt.Println(strings.SplitN("My Name is Divyanshu Shekhar.", " ", 0))
fmt.Println(strings.SplitN("This-is-Golang-Strings-Package", "-", 2))
fmt.Println(strings.SplitN("Go.exe", ".", -1))
Output:
[]
[This is-Golang-Strings-Package]
[Go exe]
Split String Using SplitAfter in Golang
The strings.SplitAfter()
function performs the same splits as the strings.Split()
function but keeps the separator.
fmt.Println(strings.SplitAfter("golang,strings,package,split,function", ","))
fmt.Println(strings.SplitAfterN("golang,strings,package,split,function", ",", 2))
Output:
[golang, strings, package, split, function]
[golang, strings,package,split,function]
SplitAfterN()
function is also available in the Golang strings package when we want to split a specific number of times.
Learn more about Golang Split String by delimiter using Split, SplitN and SplitAfter from the official Documentation.