You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152
  1. package utils
  2. // Copyright (c) 2014 Kevin Wallace <kevin@pentabarf.net>
  3. // Found here: https://github.com/kevinwallace/fieldsn
  4. // Released under the MIT license
  5. // XXX this implementation treats negative n as "return nil",
  6. // unlike stdlib SplitN and friends, which treat it as "no limit"
  7. // Original source code below:
  8. // Package fieldsn implements FieldsN and FieldsFuncN,
  9. // which are conspicuously missing from the strings package.
  10. import (
  11. "unicode"
  12. )
  13. // FieldsN is like strings.Fields, but returns at most n fields,
  14. // and the nth field includes any whitespace at the end of the string.
  15. func FieldsN(s string, n int) []string {
  16. return FieldsFuncN(s, unicode.IsSpace, n)
  17. }
  18. // FieldsFuncN is like strings.FieldsFunc, but returns at most n fields,
  19. // and the nth field includes any runes at the end of the string normally excluded by f.
  20. func FieldsFuncN(s string, f func(rune) bool, n int) []string {
  21. if n <= 0 {
  22. return nil
  23. }
  24. a := make([]string, 0, n)
  25. na := 0
  26. fieldStart := -1
  27. for i, rune := range s {
  28. if f(rune) {
  29. if fieldStart >= 0 {
  30. a = append(a, s[fieldStart:i])
  31. na++
  32. fieldStart = -1
  33. }
  34. } else if fieldStart == -1 {
  35. fieldStart = i
  36. if na+1 == n {
  37. break
  38. }
  39. }
  40. }
  41. if fieldStart >= 0 {
  42. a = append(a, s[fieldStart:])
  43. }
  44. return a
  45. }