diff options
author | Russ Cox <rsc@golang.org> | 2009-11-04 15:19:30 -0800 |
---|---|---|
committer | Russ Cox <rsc@golang.org> | 2009-11-04 15:19:30 -0800 |
commit | 786174e05dd698bbddb75ff0205e5643d53f185f (patch) | |
tree | 94e28222dec9b662825b9c883b32bc2a152130f5 /src/pkg/strings/strings.go | |
parent | 33e0a3496b36d6a92c1e54bec50edeeef7c37d67 (diff) | |
download | golang-786174e05dd698bbddb75ff0205e5643d53f185f.tar.gz |
bytes.SplitAfter and strings.SplitAfter
most common usage is:
lines := strings.SplitAfter(text, "\n", 0)
R=r
http://go/go-review/1018042
Diffstat (limited to 'src/pkg/strings/strings.go')
-rw-r--r-- | src/pkg/strings/strings.go | 23 |
1 files changed, 18 insertions, 5 deletions
diff --git a/src/pkg/strings/strings.go b/src/pkg/strings/strings.go index f4b969b42..ecfb088cd 100644 --- a/src/pkg/strings/strings.go +++ b/src/pkg/strings/strings.go @@ -79,10 +79,9 @@ func LastIndex(s, sep string) int { return -1 } -// Split splits the string s around each instance of sep, returning an array of substrings of s. -// If sep is empty, Split splits s after each UTF-8 sequence. -// If n > 0, split Splits s into at most n substrings; the last subarray will contain an unsplit remainder string. -func Split(s, sep string, n int) []string { +// 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 sep == "" { return explode(s, n) } @@ -95,7 +94,7 @@ func Split(s, sep string, n int) []string { 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]; + a[na] = s[start:i+sepSave]; na++; start = i+len(sep); i += len(sep)-1; @@ -105,6 +104,20 @@ func Split(s, sep string, n int) []string { return a[0:na+1] } +// Split splits the string s around each instance of sep, returning an array of substrings of s. +// If sep is empty, Split splits s after each UTF-8 sequence. +// If n > 0, split Splits s into at most n substrings; the last substring will be the unsplit remainder. +func Split(s, sep string, n int) []string { + return genSplit(s, sep, 0, n); +} + +// SplitAfter splits the string s after each instance of sep, returning an array of substrings of s. +// If sep is empty, SplitAfter splits s after each UTF-8 sequence. +// If n > 0, SplitAfter splits s into at most n substrings; the last substring will be the unsplit remainder. +func SplitAfter(s, sep string, n int) []string { + return genSplit(s, sep, len(sep), n); +} + // Join concatenates the elements of a to create a single string. The separator string // sep is placed between elements in the resulting string. func Join(a []string, sep string) string { |