summaryrefslogtreecommitdiff
path: root/src/pkg/bytes/bytes.go
diff options
context:
space:
mode:
authorAndrey Mirtchovski <mirtchovski@gmail.com>2009-12-15 21:09:55 -0800
committerAndrey Mirtchovski <mirtchovski@gmail.com>2009-12-15 21:09:55 -0800
commit85dc7f5943f3b6aee9702c52a0cf1db92396be74 (patch)
tree3d7ec652ac65ecba739531ceced5f43401f75113 /src/pkg/bytes/bytes.go
parent77fa44eef11a3355524e2d92c53f8b129d33b939 (diff)
downloadgolang-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.go38
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 {