What is the SplitAfter function in Golang?
Overview
The SplitAfter function is used to split a single string argument into two or more substrings at each instance of a certain substring.
To use this function, we must import the strings package in our file and access the SplitAfter function within it, using the . notation (string.SplitAfter).
Syntax
Here is the definition of the SplitAfter function:
func SplitAfter(str, sbstr string) []string
Parameters
The SplitAfter function takes two arguments:
-
str: This is the argument of typestringthat we want to split. -
sbstr: This is thestringargument that represents the substrings on which we want to split thestr.
Return value
The SplitAfter function returns the slice of str that is split upon all instances of the sbstr.
A few exceptions to this are:
-
If the
stris empty, then theSplitAfterfunction splits the string argument after each UTF-8 sequence. -
If both the input arguments are empty, then the
SplitAfterfunction returns an empty slice. -
If the
strdoes not contain thesbstr, then theSplitAfterfunction returns a slice that just contains thesbstr.
Example 1
In the code below, we use the SplitAfter function to split a sentence on all instances of the space character and then print out the first eight words in a loop:
package mainimport ("fmt""strings")func main() {str := "This is a greek letter α is used often in mathematics"x := strings.SplitAfter(str, " ")for i := 0; i < 8; i++ {fmt.Println(x[i])}}
Code explanation
- Lines 3–6: We import the
stringpackages. - Line 11: We declare a
string. - Line 12: We use the
SplitAfterfunction, which splits thestringwith spaces between the text. - Lines 13–15: We display the result.
Example 2
The following piece of code shows the return values in case either of the two arguments is empty:
package mainimport ("fmt""strings")func main() {str :=""x := strings.SplitAfter(str, "a")fmt.Println("return value when str is empty: ",x)str = "This is a greek letter α is used often in mathematics"y := strings.SplitAfter(str, "")fmt.Println("return value when sbstr is empty: ",y)}
Code explanation
- Lines 3–6: We import the
stringpackages. - Line 11: We declare a
string. - Line 12: We use the
SplitAfterfunction, which splits thestringby lettera. - Line 13: We display the result.
- Line 15: We declare a
string. - Line 16: We use the
SplitAfterfunction, which splits thestringbyempty string. - Line 17: We display the result.