golang字符串截取的两种方式
打印出时间,发现采用lastIndex要比split的方式要快一些.
直接上代码
1 | package main |
1 | func split(name string) (int,string){ |
split内部的实现可看到源码(如下),内部也是去做的for循环字符串截取分隔,所以lastIndex直接获取到索引,直接截取:1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27// Generic split: splits after each instance of sep,
// including sepSave bytes of sep in the subarrays.
func genSplit(s, sep string, sepSave, n int) []string {
if n == 0 {
return nil
}
if sep == "" {
return explode(s, n)
}
if n < 0 {
n = Count(s, sep) + 1
}
c := sep[0]
start := 0
a := make([]string, n)
na := 0
for i := 0; i+len(sep) <= len(s) && na+1 < n; i++ {
if s[i] == c && (len(sep) == 1 || s[i:i+len(sep)] == sep) {
a[na] = s[start : i+sepSave]
na++
start = i + len(sep)
i += len(sep) - 1
}
}
a[na] = s[start:]
return a[0 : na+1]
}