了解标准库是一个非常好的学习语言的方法。接下里的一些章节我们将详细研究标准库中的类型,方法,结合实际应用案例进行有趣的编程。
字符串处理是比较基础的库,我们从简单的库开始入门。
本节我们将继续用实例代码研究以下函数的用法。
func Cut(s, sep string) (before, after string, found bool)
func CutPrefix(s, prefix string) (after string, found bool)
func CutSuffix(s, suffix string) (before string, found bool)
func EqualFold(s, t string) bool
func Fields(s string) []string
func FieldsFunc(s string, f func(rune) bool) []string
func HasPrefix(s, prefix string) bool
func HasSuffix(s, suffix string) bool
package main
import (
"fmt"
"strings"
"unicode"
)
func main() {
m := "hello this is strings."
// cut用sep参数分割原字符串,返回3个参数,切割后左边部分,切割后右边部分,是否存在sep,不存在就不切割
show := func(s, sep string) {
before, after, found := strings.Cut(s, sep)
fmt.Printf("Cut(%q, %q) = %q, %q, %v\n", s, sep, before, after, found)
}
show(m, "this")
show(m, "is")
show(m, "wow")
// cutprefix用于去掉前缀,如果原字符串以sep开头就去掉这一部分,返回剩余部分,以及是否存在布尔值
show2 := func(s, sep string) {
after, found := strings.CutPrefix(s, sep)
fmt.Printf("CutPrefix(%q, %q) = %q, %v\n", s, sep, after, found)
}
show2(m, "hello")
show2(m, "this")
show2(m, "wow")
// cutsuffix用于去掉后缀,如果原字符串以sep结尾就去掉这一部分,返回剩余部分,以及是否存在布尔值
show3 := func(s, sep string) {
after, found := strings.CutSuffix(s, sep)
fmt.Printf("CutSuffix(%q, %q) = %q, %v\n", s, sep, after, found)
}
show3(m, "strings")
show3(m, "strings.")
show3(m, "wow")
// equalFold是否在utf8编码下,不区分大小写相等
fmt.Println("Go equalFold go?", strings.EqualFold("Go", "go"))
// fields用空白字符分割字符串,包括空格,多个空格,\t,\r,\n
fmt.Println("Fields are 1: ", strings.Fields(" foo bar baz "))
fmt.Println("Fields are 2: ", strings.Fields(" foo bar\t baz "))
fmt.Println("Fields are 3: ", strings.Fields(" foo bar\r\nbaz "))
// fieldsFunc根据提供的函数分割字符串,下面的f函数判断当c不是字母也不是数字的时候返回true,也就是在此处分割
f := func(c rune) bool {
return !unicode.IsLetter(c) && !unicode.IsNumber(c)
}
fmt.Println("Fields are 4: ", strings.FieldsFunc(" foo1;bar2,baz3...", f))
// hasPrefix, 区分大小写
fmt.Println(strings.HasPrefix(m, "Hello"))
// hasSuffix, 区分大小写
fmt.Println(strings.HasSuffix(m, "strings."))
}
输出:
Cut("hello this is strings.", "this") = "hello ", " is strings.", true
Cut("hello this is strings.", "is") = "hello th", " is strings.", true
Cut("hello this is strings.", "wow") = "hello this is strings.", "", false
CutPrefix("hello this is strings.", "hello") = " this is strings.", true
CutPrefix("hello this is strings.", "this") = "hello this is strings.", false
CutPrefix("hello this is strings.", "wow") = "hello this is strings.", false
CutSuffix("hello this is strings.", "strings") = "hello this is strings.", false
CutSuffix("hello this is strings.", "strings.") = "hello this is ", true
CutSuffix("hello this is strings.", "wow") = "hello this is strings.", false
Go equalFold go? true
Fields are 1: [foo bar baz]
Fields are 2: [foo bar baz]
Fields are 3: [foo bar baz]
Fields are 4: [foo1 bar2 baz3]
false
false