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

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

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 main
import (
"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 string packages.
  • Line 11: We declare a string.
  • Line 12: We use the SplitAfter function, which splits the string with 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 main
import (
"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 string packages.
  • Line 11: We declare a string.
  • Line 12: We use the SplitAfter function, which splits the string by letter a.
  • Line 13: We display the result.
  • Line 15: We declare a string.
  • Line 16: We use the SplitAfter function, which splits the string by empty string.
  • Line 17: We display the result.

Free Resources