Use the Golang strings.Split() to split the string by character using a specified delimiter character. It split a string by a character and returns the slice of substrings.
Syntax
func Split(s, sep string) []string
Where,
s = given string
sep = is the delimiter
Returns string array.
In this article, we will discuss how to use strings.Split() function in golang to split a string by character.
Golang Split String by Character using strings.Split()
Golang strings package has a built-in Split method that takes two arguments; a string and a character as delimiter to split a string.
package main import ( "fmt" "strings" ) func main() { // Split by character ! s1 := strings.Split("Hello!Welcome to Golang", "!") fmt.Println(s1) fmt.Println("The length of the slice is:", len(s1)) // Split by character s s2 := strings.Split("package", "a") fmt.Println(s2) fmt.Println("The length of the slice is:", len(s2)) }
In the above golang program, it imports strings package to use Split function and fmt package.
Golang strings Split function takes 2 arguments:
- string
- delimiter ( in our example its character)
In the first example, strings.Split() function split a string by character ! and returns a slice of substrings ( string array).
In the second example, the Split() function split a string by character a and returns a string array.
The output of the above golang program to split a string by character is:
[Hello Welcome to Golang]
The length of the slice is: 2
[p ck ge]
The length of the slice is: 3
Cool Tip: How to split string by whitespace in Golang!
Conclusion
I hope the above article on how to split a string by character in golang is helpful to you.
You can find more topics about the Golang tutorials on the GolangSpot Home page.