Open In App

strings.FieldsFunc() Function in Golang With Examples

Last Updated : 19 Apr, 2020
Comments
Improve
Suggest changes
Like Article
Like
Report
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: C
// Golang program to illustrate the
// strings.FieldsFunc() Function

package main

import (
    "fmt"
    "strings"
    "unicode"
)

func main() {

    // f is a function which returns true if the
    // c is number and false otherwise
    f := func(c rune) bool {
        return unicode.IsNumber(c)
    }

    // FieldsFunc() function splits the string passed
    // on the return values of the function f
    // String will therefore be split when a number
    // is encontered and returns all non-numbers
    fmt.Printf("Fields are: %q\n", 
       strings.FieldsFunc("ABC123PQR456XYZ789", f))
}
Output:
Fields are: ["ABC" "PQR" "XYZ"]
Example 2: C
// Golang program to illustrate the
// strings.FieldsFunc() Function
package main

import (
    "fmt"
    "strings"
    "unicode"
)

func main() {

    // f is a function which returns true if the
    // c is a white space or a full stop
    // and returns false otherwise
    f := func(c rune) bool {
        return unicode.IsSpace(c) || c == '.'
    }

    // We can also pass a string indirectly
    // The string will split when a space or a
    // full stop is encontered and returns all non-numbers
    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"]

Next Article
Article Tags :

Similar Reads