1
0
mirror of https://github.com/golang/go synced 2024-11-26 04:07:59 -07:00

strings: make Split(s, "", n) faster

R=rsc
CC=golang-dev
https://golang.org/cl/223096
This commit is contained in:
Spring Mc 2010-03-04 16:15:51 -08:00 committed by Russ Cox
parent 36c5c5bf40
commit 3dcbf73c84

View File

@ -13,24 +13,21 @@ import (
// explode splits s into an array of UTF-8 sequences, one per Unicode character (still strings) up to a maximum of n (n <= 0 means no limit). // explode splits s into an array of UTF-8 sequences, one per Unicode character (still strings) up to a maximum of n (n <= 0 means no limit).
// Invalid UTF-8 sequences become correct encodings of U+FFF8. // Invalid UTF-8 sequences become correct encodings of U+FFF8.
func explode(s string, n int) []string { func explode(s string, n int) []string {
if n <= 0 { l := utf8.RuneCountInString(s)
n = len(s) if n <= 0 || n > l {
n = l
} }
a := make([]string, n) a := make([]string, n)
var size, rune int var size, rune int
na := 0 i, cur := 0, 0
for len(s) > 0 { for ; i+1 < n; i++ {
if na+1 >= n { rune, size = utf8.DecodeRuneInString(s[cur:])
a[na] = s a[i] = string(rune)
na++ cur += size
break
} }
rune, size = utf8.DecodeRuneInString(s) // add the rest
s = s[size:] a[i] = s[cur:]
a[na] = string(rune) return a
na++
}
return a[0:na]
} }
// Count counts the number of non-overlapping instances of sep in s. // Count counts the number of non-overlapping instances of sep in s.
@ -39,11 +36,21 @@ func Count(s, sep string) int {
return utf8.RuneCountInString(s) + 1 return utf8.RuneCountInString(s) + 1
} }
c := sep[0] c := sep[0]
l := len(sep)
n := 0 n := 0
for i := 0; i+len(sep) <= len(s); i++ { if l == 1 {
if s[i] == c && (len(sep) == 1 || s[i:i+len(sep)] == sep) { // special case worth making fast
for i := 0; i < len(s); i++ {
if s[i] == c {
n++ n++
i += len(sep) - 1 }
}
return n
}
for i := 0; i+l <= len(s); i++ {
if s[i] == c && s[i:i+l] == sep {
n++
i += l - 1
} }
} }
return n return n