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
</>
Copy
strings.Split(str, sep_string)
where
stringsis the package.Splitis the function name.stris the input string.sep_stringis 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
</>
Copy
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
</>
Copy
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 Go Tutorial, we learned how to split a string in Go using strings.Split() function.
