This repository has been archived on 2015-04-29. You can view files and clone it, but cannot push or open issues or pull requests.
jsh/utils.go
2014-09-04 02:30:52 -04:00

45 lines
1015 B
Go

package jsh
import (
"math"
"unicode"
)
// FieldsN slices s into substrings after each instance of a whitespace
// character (according to unicode.IsSpace) and returns a slice of those
// substrings. The slice's length is guaranteed to be at most maxN, and
// all leftover fields are put into the last substring.
func FieldsN(s string, maxN int) []string {
// First count the fields.
n := 0
inField := false
for _, rune := range s {
wasInField := inField
inField = !unicode.IsSpace(rune)
if inField && !wasInField {
n++
}
}
n = int(math.Min(float64(n), float64(maxN)))
// Now create them.
a := make([]string, n)
na := 0
fieldStart := -1 // Set to -1 when looking for start of field.
for i, rune := range s {
if unicode.IsSpace(rune) && na+1 < maxN {
if fieldStart >= 0 {
a[na] = s[fieldStart:i]
na++
fieldStart = -1
}
} else if fieldStart == -1 {
fieldStart = i
}
}
if fieldStart >= 0 { // Last field might end at EOF.
a[na] = s[fieldStart:]
}
return a
}