strings.FieldsFunc() Function in Golang With Examples
Last Updated :
19 Apr, 2020
strings.FieldsFunc() Function in Golang is used to splits the given string str at each run of Unicode code points c satisfying f(c) and returns an array of slices of str.
Syntax:
func FieldsFunc(str string, f func(rune) bool) []string
Here, str is the given string, the rune is a built-in type meant to contain a single Unicode character and f is a user-defined function.
Return: If all code points in str satisfy f(c) or the string is empty, an empty slice is returned.
Note: This function makes no guarantees about the order in which it calls f(c). If f does not return consistent results for a given c, FieldsFunc may crash.
Example 1:
package main
import (
"fmt"
"strings"
"unicode"
)
func main() {
f := func(c rune) bool {
return unicode.IsNumber(c)
}
fmt.Printf( "Fields are: %q\n" ,
strings.FieldsFunc( "ABC123PQR456XYZ789" , f))
}
|
Output:
Fields are: ["ABC" "PQR" "XYZ"]
Example 2:
package main
import (
"fmt"
"strings"
"unicode"
)
func main() {
f := func(c rune) bool {
return unicode.IsSpace(c) || c == '.'
}
s := "We are humans. We are social animals."
fmt.Printf( "Fields are: %q\n" , strings.FieldsFunc(s, f))
}
|
Output:
Fields are: ["We" "are" "humans" "We" "are" "social" "animals"]
Share your thoughts in the comments
Please Login to comment...