How to split string in Golang? [SOLVED]


Written By - Tuan Nguyen
Advertisement

Strings in the Go language are different from those in other languages like Java, C++, Python, etc. It is a sequence of characters with various widths, where each character is encoded as one or more bytes using UTF-8 encoding. With the aid of the following functions, you are able to divide a string into a slice in Go strings. Since these functions are defined in the strings package, your program must import the strings package in order to access them:

import "strings"

 

Example 1: Split a string by commas or other substrings with strings.Split() function

func Split(s, sep string) []string:Split slices s into all substrings separated by sep and returns a slice of the substrings between those separators. If s does not contain sep and sep is not empty, Split returns a slice of length 1 whose only element is s. If sep is empty, Split splits after each UTF-8 sequence. If both s and sep are empty, Split returns an empty slice.

Here is an example of splitting a string by Split() function:

package main

import (
	"fmt"
	"strings"
)

func main() {
	fmt.Printf("%q\n", strings.Split("this,is,a,split,string,example", ","))
	fmt.Printf("%q\n", strings.Split("this cat this dog this red horse ", "this "))
	fmt.Printf("%q\n", strings.Split(" Hello Go Linux Cloud Member ", ""))
	fmt.Printf("%q\n", strings.Split("", "Empty input"))
}

Output:

["this" "is" "a" "split" "string" "example"]
["" "cat " "dog " "red horse "]
[" " "H" "e" "l" "l" "o" " " "G" "o" " " "L" "i" "n" "u" "x" " " "C" "l" "o" "u" "d" " " "M" "e" "m" "b" "e" "r" " "]
[""]

 

Example 2: Using SplitAfter() function to include the separator

func SplitAfter(s, sep string) []string: SplitAfter slices s into all substrings after each instance of sep and returns a slice of those substrings. If s does not contain sep and sep is not empty, SplitAfter returns a slice of length 1 whose only element is s. If sep is empty, SplitAfter splits after each UTF-8 sequence. If both s and sep are empty, SplitAfter returns an empty slice.

Here is an example of splitting a slit with the separator:

package main

import (
	"fmt"
	"strings"
)

func main() {
	fmt.Printf("%q\n", strings.SplitAfter("this,is,a,split,string,example", ","))
}

Output:

["this," "is," "a," "split," "string," "example"]

Noted: To split only the first n values, use strings.SplitN and strings.SplitAfterN.

Advertisement

 

Example 3: Split by whitespace or newline using Fields() function

func Fields(s string) []string: Fields splits the string s around each instance of one or more consecutive white space characters, as defined by unicode.IsSpace, returning a slice of substrings of s or an empty slice if s contains only white space.

The below code shows how to use Fields() function to split by whitespace or newline:

package main

import (
	"fmt"
	"strings"
)

func main() {
	fmt.Printf("Simple split: %q", strings.Split(" \t \n this is  split example \n \t  ", ""))
	fmt.Println("")
	fmt.Printf("Fields split: %q", strings.Fields(" \t \n this is  split example \n \t  "))
	fmt.Println("")
}

Output:

Simple split: [" " "\t" " " "\n" " " "t" "h" "i" "s" " " "i" "s" " " " " "s" "p" "l" "i" "t" " " "e" "x" "a" "m" "p" "l" "e" " " "\n" " " "\t" " " " "]
Fields split: ["this" "is" "split" "example"]

 

Example 4: Using FieldsFunc() to handle custom separator

func FieldsFunc(s string, f func(rune) bool) []string: FieldsFunc splits the string s at each run of Unicode code points c satisfying f(c) and returns an array of slices of s. If all code points in s satisfy f(c) or the string is empty, an empty slice is returned.

Here is an example of splitting a string whose separator is a numeric character:

package main

import (
	"fmt"
	"strings"
	"unicode"
)

func main() {
	f := func(c rune) bool {
                // check if character is numeric
		return unicode.IsNumber(c)
	}
	fmt.Printf("Result: %q", strings.FieldsFunc("This1 is 1 example of 6splitting string w7ith 2custom3 separator", f))
	fmt.Println("")
}

Output:

Result: ["This" " is " " example of " "splitting string w" "ith " "custom" " separator"]

 

Example 5: Split string with regular expression

The regexp Split approach might work in more difficult conditions. A regular expression is used to separate the string's substrings. The method accepts an integer n as an argument, returning a maximum of n substrings if n >= 0.

Here is an example of splitting a string with a regular expression (split by 2 commas and 1 space):

Advertisement
package main

import (
	"fmt"
	"regexp"
)

func main() {
	h := regexp.MustCompile(`h`) // single `h`
	fmt.Printf("%q\n", h.Split("kihihaha", -1))
	fmt.Printf("%q\n", h.Split("kihihaha", 0))
	fmt.Printf("%q\n", h.Split("kihihaha", 1))
	fmt.Printf("%q\n", h.Split("kihihaha", 2))

	zp := regexp.MustCompile(` *,, *`) // 2 commas and 1 space
	fmt.Printf("%q\n", zp.Split("This,is, an,, example of split, , string with,, expression, c ", -1))
}

Output:

["ki" "i" "a" "a"]
[]
["kihihaha"]
["ki" "ihaha"]
["This,is, an" "example of split, , string with" "expression, c "]

 

Summary

The Golang strings library's Split() function divides a string into a list of substrings by using a predefined separator. For more complex cases, we can use the Fields()  function or regular expression. With explained examples above, I hope you have a better understanding of how to split a string into a slice in Golang.

 

References

https://en.wikipedia.org/wiki/UTF-8
https://pkg.go.dev/strings
https://en.wikipedia.org/wiki/Regular_expression

 

Didn't find what you were looking for? Perform a quick search across GoLinuxCloud

If my articles on GoLinuxCloud has helped you, kindly consider buying me a coffee as a token of appreciation.

Buy GoLinuxCloud a Coffee

For any other feedbacks or questions you can either use the comments section or contact me form.

Thank You for your support!!

Leave a Comment