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.

62 lines
1.4 KiB

9 years ago
  1. package strings
  2. import (
  3. "fmt"
  4. "strings"
  5. )
  6. // SplitAndTrimEmpty slices s into all subslices separated by sep and returns a
  7. // slice of the string s with all leading and trailing Unicode code points
  8. // contained in cutset removed. If sep is empty, SplitAndTrim splits after each
  9. // UTF-8 sequence. First part is equivalent to strings.SplitN with a count of
  10. // -1. also filter out empty strings, only return non-empty strings.
  11. func SplitAndTrimEmpty(s, sep, cutset string) []string {
  12. if s == "" {
  13. return []string{}
  14. }
  15. spl := strings.Split(s, sep)
  16. nonEmptyStrings := make([]string, 0, len(spl))
  17. for i := 0; i < len(spl); i++ {
  18. element := strings.Trim(spl[i], cutset)
  19. if element != "" {
  20. nonEmptyStrings = append(nonEmptyStrings, element)
  21. }
  22. }
  23. return nonEmptyStrings
  24. }
  25. // ASCIITrim removes spaces from an a ASCII string, erroring if the
  26. // sequence is not an ASCII string.
  27. func ASCIITrim(s string) (string, error) {
  28. if len(s) == 0 {
  29. return "", nil
  30. }
  31. r := make([]byte, 0, len(s))
  32. for _, b := range []byte(s) {
  33. switch {
  34. case b == 32:
  35. continue // skip space
  36. case 32 < b && b <= 126:
  37. r = append(r, b)
  38. default:
  39. return "", fmt.Errorf("non-ASCII (non-tab) char 0x%X", b)
  40. }
  41. }
  42. return string(r), nil
  43. }
  44. // StringSliceEqual checks if string slices a and b are equal
  45. func StringSliceEqual(a, b []string) bool {
  46. if len(a) != len(b) {
  47. return false
  48. }
  49. for i := 0; i < len(a); i++ {
  50. if a[i] != b[i] {
  51. return false
  52. }
  53. }
  54. return true
  55. }