Home » Golang String Split with an Examples

Golang String Split with an Examples

The Split () method of strings package in golang is used to split a string into slices. The Split () method accepts a string as a parameter and separator to slice the string into substrings. It returns the substrings.

In this article, we will discuss how to split a string into slices using different ways in golang like the Split(), and SplitAfter() methods of the strings package.

Split String into Substring using Split()

Use the Split() method of the strings package in golang to split a string into substrings separated by a separator.

To split a string into substrings using Split():

  1. Import the strings package
  2. Use the strings.Split() method to split a string into slices
  3. Pass the string and separator to the Split() method
  4. The Split () method returns substrings between that separator
package main

import (
	"fmt"
	"strings"
)

func main() {
	str := "Split,string,into,substrings,using,split(),method"
	// Split the string into substrings separated by ,
	s_value := strings.Split(str, ",")
	fmt.Println(s_value)
	fmt.Println("The length of the slice is:", len(s_value))
}

In the above golang program, the Split() method takes a string as input and separator as “,”. It splits the string by a comma and returns the substrings.

The output of the above golang program is:

[Split string into substrings using split() method]

The length of the slice is: 7

Use SplitAfter() to split String into substrings

SplitAfter() method of strings package in golang slices the string into all substrings after the specified separator and returns a slice of those substrings.

To Split String into slices using SplitAfter():

  1. Import the strings package
  2. Use strings.SplitAfter() method to split a string into substrings.
  3. Pass the string and separator to split the string.
  4. SplitAfter() returns a slice of substrings. It doesn’t delete the separator.
package main

import (
	"fmt"
	"strings"
)

func main() {
	str := "Use split(),SplitAfter(), method to split string into substrings"
	// Split the string into substrings separated by ,
	s_value := strings.SplitAfter(str, ",")
	fmt.Println(s_value)
	fmt.Println("The length of the slice is:", len(s_value))
}

The output of the above golang program returns the slices of substring as given below:

[Use split(), SplitAfter(),  method to split string into substrings]

The length of the slice is: 3

Note here, SplitAfter() method doesn’t remove the specified separator when it split the string.

Conclusion

I hope the above article on how to split the string into substrings using the Split() and SplitAfter() methods of the strings package is helpful to you.

You can find more topics about the Golang tutorials on the GolangSpot Home page.

Leave a Comment