strings.FieldFunc()
functionIn Golang, the FieldsFunc()
function is a built-in function of the strings package. It splits a string into slices of substrings based on the given function.
func FieldsFunc(str string, f func(rune) bool) []string
str
is the given string.f
is a function that checks all Unicode characters.The return type of this function is a string
.
The FieldsFunc()
function returns a slice of substrings if the condition is satisfied.
Note: If the string is empty it returns an empty slice.
The following code shows how to use the FieldsFunc()
function:
Note: To access the string package’s functions, you must import the
string
andUnicode
packages into your program.
package main
import (
"fmt"
"strings"
"unicode"
)
// Golang program// demostrating how to use strings.FieldsFunc() Functionpackage mainimport ("fmt""strings""unicode")func main() {myFunc := func(c rune) bool {return unicode.IsNumber(c)}// When a number is encountered,// the FieldsFunc() method separates the string// and returns all non-numbers.fmt.Printf("The Fields are: %q\n",strings.FieldsFunc("This018is92a6shot179on89Golang864string34FieldFunc", myFunc))}
Line 5: We add the main
package.
Lines 7 to 11: We import the necessary packages in the Golang project.
Lines 13 to 24: We define the main()
function. In the main, we create a function to find if the value is a number and the return value is assigned to the variable myFunc
. Next, we pass the variable in the strings.FieldsFunc()
function, which separates the string and returns all non-numbers when a number is encountered.