背景
这个功能的实现对于任何人来说都是一个十分简单的事情,但是在go的strings标准库中有一个函数可以帮助我们减少代码量
实现
函数
func FieldsFunc(s string , f func( rune ) bool ) [] string
官方描述
FieldsFunc splits the string s at each run of Unicode code points c satisfying f© and returns an array of slices of s. If all code points in s satisfy f© or the string is empty, an empty slice is returned.
FieldsFunc makes no guarantees about the order in which it calls f© and assumes that f always returns the same value for a given c.
简单解释就是传入要分隔的字符串s和一个对字符串中字符进行判断并返回布尔值的函数f,当f返回true的位置进行分隔,最终返回一个string切片。
实现案例
package main
import (
"fmt"
"strings"
"unicode"
)
func main() {
//判断函数
f := func(c rune) bool {
//当传入的c既不是字母也不是数字时,返回true,否则返回false
return !unicode.IsLetter(c) && !unicode.IsNumber(c)
}
//对字符串分割结果进行输出
fmt.Printf("Fields are: %q", strings.FieldsFunc(" foo1;bar2,baz3...", f))
}
这个也是官方包里自带的例子,实现通过符号进行分割的功能,我在代码中加上了中文注释。