Golang FieldsFunc to Split String

Golang FieldsFunc to Split String

In the previous blog, we learned how to split string in Golang. This time we will learn about the Golang FieldsFunc function present in the strings package.

In this example, we will use the Golang FieldsFunc to split string by space delimiter.

Learn about How to Split String in Golang using Split, SplitN, and SplitAfter Functions.

Let’s learn about FieldsFunc.

Golang FieldFunc

The strings.FieldsFunc() function takes a string and a reference to a function with the signature func(rune) bool.

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

The FieldsFunc in the example below has been provided with an anonymous function as the function is small and not used anywhere else.

The strings.FieldsFunc() function iterates over every character in the string it is given and calls the function it is passed as its second argument with each character. If the called function returns true a split is performed.

Split String by Space using Golang FieldsFunc

In this example, we are looping over an array of strings and the Golang FieldsFunc will be acted upon every string in the array.

Inside the loop, we are using fmt.Printf() to print the output given by the FieldsFunc Function.

Inside the FieldsFunc Function, we use switch case to find the comma delimiter. whenever comma is encountered the function returns true else false.

When true is returned by the FieldsFunc Function, it prints the whole string without the delimiter character or rune.

In this way the string is split into array by the delimiter.

func main() {
	for _, v := range []string{"Golang,strings-package", "Hello,World !", "A-String"} {
		fmt.Printf("%q\n", strings.FieldsFunc(v, func(ch rune) bool {
			switch ch {
			case ',':
				return true
			}
			return false
		}))
	}

}
["Golang" "strings-package"]
["Hello" "World !"]
["A-String"]

Learn more aboutĀ Golang Strings Package from theĀ official Documentation.

Tags: ,

Leave a Reply

Your email address will not be published. Required fields are marked *