📜  字符串.FieldsFunc() Golang函数示例

📅  最后修改于: 2021-10-25 02:06:07             🧑  作者: Mango

字符串.FieldsFunc() Golang 中的函数用于在每次运行满足 f(c) 的 Unicode 代码点 c 时拆分给定的字符串str 并返回 str 切片的数组。

注意:此函数不保证它调用 f(c) 的顺序。如果 f 没有为给定的 c 返回一致的结果,则 FieldsFunc 可能会崩溃。

示例 1:

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

输出:

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

示例 2:

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

输出:

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