Trusted answers to developer questions
Trusted Answers to Developer Questions

Related Tags

golang
strings
communitycreator

How to use strings.FieldsFunc() in Golang

Maria Elijah

Golang strings.FieldFunc() function

In 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.

Syntax

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

Parameters

  • str is the given string.
  • f is a function that checks all Unicode characters.

Return type

The return type of this function is a string.

Return value

The FieldsFunc() function returns a slice of substrings if the condition is satisfied.

Note: If the string is empty it returns an empty slice.

Code

The following code shows how to use the FieldsFunc() function:

Note: To access the string package’s functions, you must import the string and Unicode packages into your program.

package main
  
import (
    "fmt"
    "strings"
    "unicode"
)
  

// Golang program
// demostrating how to use strings.FieldsFunc() Function
  
package main
  
import (
    "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))
}
The `FieldsFunc()` method in action

Code explanation

  • 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.

RELATED TAGS

golang
strings
communitycreator
RELATED COURSES

View all Courses

Keep Exploring