strings.FieldsFunc() Golang中的函數用於在每次運行的滿足f(c)的Unicode代碼點c處拆分給定的字符串str,並返回由str組成的切片數組。
用法:
func FieldsFunc(str string, f func(rune) bool) []string
此處,str是給定的字符串,符文是內置類型,意為包含單個Unicode字符,f是用戶定義的函數。
返回:如果str中的所有代碼點均滿足f(c)或字符串為空,則返回空片。
注意:此函數不能保證調用f(c)的順序。如果f對於給定的c沒有返回一致的結果,則FieldsFunc可能會崩潰。
範例1:
// 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))
}
輸出:
Fields are:["ABC" "PQR" "XYZ"]
範例2:
// 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))
}
輸出:
Fields are:["We" "are" "humans" "We" "are" "social" "animals"]
相關用法
- Golang math.Lgamma()用法及代碼示例
- Golang math.Float64bits()用法及代碼示例
- Golang atomic.AddInt64()用法及代碼示例
- Golang atomic.StoreInt64()用法及代碼示例
- Golang reflect.FieldByIndex()用法及代碼示例
- Golang string.Contains用法及代碼示例
- Golang bits.Sub()用法及代碼示例
- Golang io.PipeWriter.CloseWithError()用法及代碼示例
- Golang time.Round()用法及代碼示例
- Golang reflect.AppendSlice()用法及代碼示例
- Golang reflect.ChanOf()用法及代碼示例
- Golang flag.Bool()用法及代碼示例
- Golang time.Sleep()用法及代碼示例
- Golang time.Time.Year()用法及代碼示例
- Golang reflect.DeepEqual()用法及代碼示例
- Golang reflect.Indirect()用法及代碼示例
- Golang reflect.CanAddr()用法及代碼示例
- Golang reflect.CanInterface()用法及代碼示例
- Golang reflect.CanSet()用法及代碼示例
- Golang reflect.Cap()用法及代碼示例
注:本文由純淨天空篩選整理自vanigupta20024大神的英文原創作品 strings.FieldsFunc() Function in Golang With Examples。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。