diff options
author | Andrey Mirtchovski <mirtchovski@gmail.com> | 2009-12-15 21:09:55 -0800 |
---|---|---|
committer | Andrey Mirtchovski <mirtchovski@gmail.com> | 2009-12-15 21:09:55 -0800 |
commit | 85dc7f5943f3b6aee9702c52a0cf1db92396be74 (patch) | |
tree | 3d7ec652ac65ecba739531ceced5f43401f75113 /src/pkg/bytes/bytes.go | |
parent | 77fa44eef11a3355524e2d92c53f8b129d33b939 (diff) | |
download | golang-85dc7f5943f3b6aee9702c52a0cf1db92396be74.tar.gz |
bytes, strings: add new function Fields
R=rsc, r, phf
CC=golang-dev
http://codereview.appspot.com/170046
Committer: Russ Cox <rsc@golang.org>
Diffstat (limited to 'src/pkg/bytes/bytes.go')
-rw-r--r-- | src/pkg/bytes/bytes.go | 38 |
1 files changed, 38 insertions, 0 deletions
diff --git a/src/pkg/bytes/bytes.go b/src/pkg/bytes/bytes.go index 0a2146413..d69af0136 100644 --- a/src/pkg/bytes/bytes.go +++ b/src/pkg/bytes/bytes.go @@ -163,6 +163,44 @@ func SplitAfter(s, sep []byte, n int) [][]byte { return genSplit(s, sep, len(sep), n) } +// Fields splits the array s around each instance of one or more consecutive white space +// characters, returning a slice of subarrays of s or an empty list if s contains only white space. +func Fields(s []byte) [][]byte { + n := 0 + inField := false + for i := 0; i < len(s); { + rune, size := utf8.DecodeRune(s[i:]) + wasInField := inField + inField = !unicode.IsSpace(rune) + if inField && !wasInField { + n++ + } + i += size + } + + a := make([][]byte, n) + na := 0 + fieldStart := -1 + for i := 0; i <= len(s) && na < n; { + rune, size := utf8.DecodeRune(s[i:]) + if fieldStart < 0 && size > 0 && !unicode.IsSpace(rune) { + fieldStart = i + i += size + continue + } + if fieldStart >= 0 && (size == 0 || unicode.IsSpace(rune)) { + a[na] = s[fieldStart:i] + na++ + fieldStart = -1 + } + if size == 0 { + break + } + i += size + } + return a[0:na] +} + // Join concatenates the elements of a to create a single byte array. The separator // sep is placed between elements in the resulting array. func Join(a [][]byte, sep []byte) []byte { |