本文共 2782 字,大约阅读时间需要 9 分钟。
在go中的字符串是不可变字节序列,默认是UTF-8编码存储Unicode字符
主要有:
Split和SplitN函数用于分割字符串,函数原型:
func Split(s, sep string) []string 接收两个参数,s代表原串,sep代表分隔符,返回一个string切片func SplitN(s, sep string, n int) []string接收三个参数,s代表原串,sep代表分隔符,n为字段的返回一个长度为n的string切片如果sep是空则对每一个字符进行拆分 s中没有sep则返回一个长度为一的切片,内容是sSplit示例: var str string str = "hello world!" tmp := strings.Split(str, " ") fmt.Println(len(tmp), tmp) // 2, hello worldSplitN示例 tmp := strings.SplitN(str, "o ", 3)for _, v := range tmp{ fmt.Println(v)}fmt.Println("tmp len:", len(tmp))
SplitAfter和SplitAfterN函数分割字符串,但是会包含sep
SplitAfter(s, sep string) []stringSplitAfterN(s, sep string, n int) []string SplitAfter示例: tmp := strings.SplitAfter(str, "o ") for _, v := range tmp{ fmt.Println(v) } fmt.Println("tmp len:", len(tmp))SplotAfterN示例: tmp := strings.SplitAfterN(str, "o ", 3) for _, v := range tmp{ fmt.Println(v) } fmt.Println("tmp len:", len(tmp))
上面四个函数内部都调用函数func genSplit(s, sep string, sepSave, n int) []string
func genSplit(s, sep string, sepSave, n int) []string { ... if sep == "" { return explode(s, n) } if n < 0 { n = Count(s, sep) + 1 } ... m := Index(s, sep) ....}n不能等于0,n必须大于0或者小于0sep==""时使用explode将s中的字符全部拆分如果n小于0时需要根据s和sep来计算出s中sep的个数函数是CountIndex返回s中sep的第一个实例索引
Index函数用于返回s中substr的下标
func Index(s, substr string) int
不但是一个外部接口也是被内部函数所使用func Contains(s, substr string) bool
func testCtains(str, subStr string){ if strings.Contains(str, subStr){ fmt.Println("Exist",) } else { fmt.Println("Not exist") } }
和Index相似的函数有
IndexAny(s, chars string)
返回chars在s中的找到的第一个实例索引LastIndexByte(s string, c byte) int
返回字符c在s中的最后一个实例索引将a的字符串连接起来,以sep为间隔符
func Join(a []string, sep string) string
示例:
strs := make([]string, 0) for i := 0; i < 5; i ++{ strs = append(strs, "hello") } str := strings.Join(strs, "-") fmt.Println(str)
join源码:
func Join(a []string, sep string) string { switch len(a) { case 0: return "" case 1: return a[0] case 2: // Special case for common small values. // Remove if golang.org/issue/6714 is fixed return a[0] + sep + a[1] case 3: // Special case for common small values. // Remove if golang.org/issue/6714 is fixed return a[0] + sep + a[1] + sep + a[2] } //计算出结果字符串的大小 n := len(sep) * (len(a) - 1) for i := 0; i < len(a); i++ { n += len(a[i]) } b := make([]byte, n) bp := copy(b, a[0]) for _, s := range a[1:] { bp += copy(b[bp:], sep) bp += copy(b[bp:], s) } return string(b)}代码中是根据a的大小来进行操作,小于三时处理方式比较简单使用+如果len(a)过大时使用遍历
转载地址:http://rdfkb.baihongyu.com/