Home »
Golang »
Golang Reference
Golang strings.FieldsFunc() Function with Examples
Golang | strings.FieldsFunc() Function: Here, we are going to learn about the FieldsFunc() function of strings package with its usages, syntax, and examples.
Submitted by IncludeHelp, on August 16, 2021
strings.FieldsFunc()
The FieldsFunc() function is an inbuilt function of strings package which is used to split the given string into slices of substrings based on the given function. It accepts two parameters – the first one is the string and the other one is the function having the condition to be checked with all Unicode code points of the string. It returns a slice of substrings if the function satisfies the condition applied on all code points of the string. If the string is empty, it returns an empty slice.
Syntax
func FieldsFunc(str string, f func(rune) bool) []string
Parameters
- str: String from which we have to find the slice of substrings.
- f : Function.
Return Value
The return type of FieldsFunc() function is a []string, it returns a slice of substrings if the function satisfies the condition applied on all code points of the string. If the string is empty, it returns an empty slice.
Example
// Golang program to demonstrate the
// example of strings.FieldsFunc() Function
package main
import (
"fmt"
"strings"
"unicode"
)
func main() {
myfunc1 := func(c rune) bool {
return unicode.IsNumber(c)
}
myfunc2 := func(c rune) bool {
return !unicode.IsNumber(c)
}
myfunc3 := func(c rune) bool {
return unicode.IsNumber(c) && unicode.IsLetter(c)
}
// prints slices without numbers
fmt.Printf("%q\n", strings.FieldsFunc("Hello123 Hi10 Okay ...", myfunc1))
// prints slices with numbers only
fmt.Printf("%q\n", strings.FieldsFunc("Hello123 Hi10 Okay ...", myfunc2))
// prints slices with and without numbers
fmt.Printf("%q\n", strings.FieldsFunc("Hello123 Hi10 Okay ...", myfunc3))
}
Output:
["Hello" " Hi" " Okay ..."]
["123" "10"]
["Hello123 Hi10 Okay ..."]
Golang strings Package Functions »