Golang library has provided the split
function in strings
package to split the string by a separator and return the slice of substrings.
Split
Syntax
func Split(s, sep string) []string
Split the string by separator ,
. Don't forget the white space.
package main
import (
"fmt"
"strings"
)
func main() {
var greeting string = "Namaste, India"
// separate string using ', '
arr := strings.Split(greeting, ", ")
fmt.Println(arr)
}
Output
[Namaste India]
func SplitAfter
SplitAfter function split the string after the separator. It is useful when you want to include the sperator.
var greeting string = "Namaste, India"
// separate string using ', '
arr := strings.SplitAfter(greeting, ", ")
fmt.Println(arr)
Output
[Namaste, India]
There are other Split variation available in golang. Like SplitAfterN, SplitN
func Fields
Fields split the strings by n consecutive white spaces around a string.
var greeting string = "Happy New Year"
// separate string using n white spaces
arr := strings.Fields(greeting)
fmt.Println(arr)
Output
[Happy New Year]