Home ยป How to Split String with Multiple Separators in Golang

How to Split String with Multiple Separators in Golang

Use the strings.FieldsFunc() function in golang to split a string based on the given function. In the function, specify conditions to check for multiple separators, and split a string with multiple separators.

Syntax

func FieldsFunc(s string, f func(rune) bool) []string

Where,

s = given string

f = function that checks all Unicode code points c satisfying the condition.

Returns string array.

In this article, we will discuss how to split a string with multiple separators using the strings.FieldsFunc() function.

How to Split String with Multiple Separators Using FieldsFunc in Golang

The Golang strings package has a built-in FieldsFunc() method that takes two arguments; a string and a function. It splits the string at each run of Unicode code point c satisfying the condition.

package main

import (
	"fmt"
	"strings"
)

func main() {

	// Declare a string
	s1 := "192.168.1.0:1000"

	f := func(c rune) bool {
		return c == '.' || c == ':'
	}

	// Use FieldsFunc to split the string based on function
	str := strings.FieldsFunc(s1, f)

	// Print the string array
	fmt.Printf("Fields are: %q", str)
	fmt.Println("Length of the string array:", len(str))
}

In the above golang program, it imports strings package to use FieldsFunc and fmt package.

To split the string with multiple separators in a string using FieldsFunc, follow the below steps:

  1. Declare string s1
  2. Create a function that checks for Unicode character is equal to dot (.) or colon (:) returns a value, and assigns it to variable f.
  3. Call the function strings.FieldsFunc(s1, f) to split the string on multiple separators like dot and colon.
  4. Print the string array

The output of the above golang program splits a string by multiple separators, and splits a string by dot and colon.

Fields are: ["192" "168" "1" "0" "1000"]

Length of the string array: 5

Cool Tip: How to split a string and ignore an empty field in Golang!

Conclusion

I hope the above article on how to split a string with multiple separators using FieldsFunc is helpful to you.

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

Leave a Comment