當前位置: 首頁>>編程示例 >>用法及示例精選 >>正文


Golang strings.FieldsFunc()用法及代碼示例

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"]



相關用法


注:本文由純淨天空篩選整理自vanigupta20024大神的英文原創作品 strings.FieldsFunc() Function in Golang With Examples。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。