Splitting the string after the specified separator in Golang


Splitting a string after a specified separator is a common operation in many programming languages, including Golang. In Golang, the strings package provides several functions to split a string after a specified separator.

In this article, we will discuss how to split a string after a specified separator in Golang.

Using strings.SplitAfter()

The strings.SplitAfter() function is used to split a string after a specified separator. It takes two arguments: the string to be split and the separator after which to split the string. The function returns a slice of strings.

Example

Here's an example code that demonstrates how to use strings.SplitAfter() to split a string after a specified separator −

package main

import (
   "fmt"
   "strings"
)

func main() {
   str := "apple,banana,orange"
   separator := ","
   result := strings.SplitAfter(str, separator)
   fmt.Println(result) // Output: [apple, banana, orange]
}

Output

[apple, banana, orange]

In the above code, the strings.SplitAfter() function is used to split the string str after the separator ,. The function returns a slice of strings containing the substrings after the separator. The fmt.Println() function is used to print the result.

Using strings.SplitAfterN()

The strings.SplitAfterN() function is similar to strings.SplitAfter(), but it splits the string after a specified separator only a specified number of times. It takes three arguments: the string to be split, the separator after which to split the string, and the maximum number of splits. The function returns a slice of strings.

Example

Here's an example code that demonstrates how to use strings.SplitAfterN() to split a string after a specified separator only a specified number of times −

package main

import (
   "fmt"
   "strings"
)

func main() {
   str := "apple,banana,orange"
   separator := ","
   maxSplits := 2
   result := strings.SplitAfterN(str, separator, maxSplits)
   fmt.Println(result) // Output: [apple, banana,orange]
}

Output

[apple, banana,orange]

In the above code, the strings.SplitAfterN() function is used to split the string str after the separator , only 2 times. The function returns a slice of strings containing the substrings after the separator. The fmt.Println() function is used to print the result.

Conclusion

Splitting a string after a specified separator is a common operation in Golang. The strings package provides several functions to split a string after a specified separator. In this article, we discussed how to use strings.SplitAfter() and strings.SplitAfterN() functions to split a string after a specified separator in Golang.

Updated on: 19-Apr-2023

892 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements