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
strings
is the package.Split
is the function name.str
is the input string.sep_string
is the delimiter or separator.
strings.Split() function returns string array []string
.
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.