strings.FieldsFunc() Function in Golang With Examples

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:

filter_none

edit
close

play_arrow

link
brightness_4
code

// 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))
}

chevron_right


Output:

Fields are: ["ABC" "PQR" "XYZ"]

Example 2:

filter_none

edit
close

play_arrow

link
brightness_4
code

// 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))
}

chevron_right


Output:

Fields are: ["We" "are" "humans" "We" "are" "social" "animals"]



My Personal Notes arrow_drop_up

Check out this Author's contributed articles.

If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.


Article Tags :

2


Please write to us at contribute@geeksforgeeks.org to report any issue with the above content.