String Split in Golang

Tuesday, December 15, 2020 • One minute to read

Golangto-the-pointgolangstring

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

1func Split(s, sep string) []string

Split the string by separator , . Don't forget the white space.

 1package main
 2
 3import (
 4	"fmt"
 5	"strings"
 6)
 7
 8func main() {
 9	var greeting string = "Namaste, India"
10
11	// separate string using ', '
12	arr := strings.Split(greeting, ", ")
13	fmt.Println(arr)
14}

Output

1[Namaste India]

Try it

func SplitAfter

SplitAfter function split the string after the separator. It is useful when you want to include the sperator.

1var greeting string = "Namaste, India"
2
3// separate string using ', '
4arr := strings.SplitAfter(greeting, ", ")
5fmt.Println(arr)

Output

1[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.

1var greeting string = "Happy                 New   Year"
2// separate string using n white spaces
3arr := strings.Fields(greeting)
4fmt.Println(arr)

Output

1[Happy New Year]

Golangto-the-pointgolangstring

PreviousConvert Hexadecimal to Decimal and Decimal to Hexadecimal in Golang

NextRemove an Element From an Array Using Filter in Nodejs