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
).
Here is the definition of the SplitAfter
function:
func SplitAfter(str, sbstr string) []string
The SplitAfter
function takes two arguments:
str
: This is the argument of type string
that we want to split.
sbstr
: This is the string
argument that represents the substrings on which we want to split the str
.
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 str
is empty, then the SplitAfter
function splits the string argument after each UTF-8 sequence.
If both the input arguments are empty, then the SplitAfter
function returns an empty slice.
If the str
does not contain the sbstr
, then the SplitAfter
function returns a slice that just contains the sbstr
.
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])}}
string
packages.string
.SplitAfter
function, which splits the string
with spaces between the text.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)}
string
packages.string
.SplitAfter
function, which splits the string
by letter a
.string
.SplitAfter
function, which splits the string
by empty string
.