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.

100 lines
2.3 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. // StringInSlice returns true if a is found the list.
  26. func StringInSlice(a string, list []string) bool {
  27. for _, b := range list {
  28. if b == a {
  29. return true
  30. }
  31. }
  32. return false
  33. }
  34. // SplitAndTrim slices s into all subslices separated by sep and returns a
  35. // slice of the string s with all leading and trailing Unicode code points
  36. // contained in cutset removed. If sep is empty, SplitAndTrim splits after each
  37. // UTF-8 sequence. First part is equivalent to strings.SplitN with a count of
  38. // -1.
  39. func SplitAndTrim(s, sep, cutset string) []string {
  40. if s == "" {
  41. return []string{}
  42. }
  43. spl := strings.Split(s, sep)
  44. for i := 0; i < len(spl); i++ {
  45. spl[i] = strings.Trim(spl[i], cutset)
  46. }
  47. return spl
  48. }
  49. // Returns true if s is a non-empty printable non-tab ascii character.
  50. func IsASCIIText(s string) bool {
  51. if len(s) == 0 {
  52. return false
  53. }
  54. for _, b := range []byte(s) {
  55. if 32 <= b && b <= 126 {
  56. // good
  57. } else {
  58. return false
  59. }
  60. }
  61. return true
  62. }
  63. // NOTE: Assumes that s is ASCII as per IsASCIIText(), otherwise panics.
  64. func ASCIITrim(s string) string {
  65. r := make([]byte, 0, len(s))
  66. for _, b := range []byte(s) {
  67. switch {
  68. case b == 32:
  69. continue // skip space
  70. case 32 < b && b <= 126:
  71. r = append(r, b)
  72. default:
  73. panic(fmt.Sprintf("non-ASCII (non-tab) char 0x%X", b))
  74. }
  75. }
  76. return string(r)
  77. }
  78. // StringSliceEqual checks if string slices a and b are equal
  79. func StringSliceEqual(a, b []string) bool {
  80. if len(a) != len(b) {
  81. return false
  82. }
  83. for i := 0; i < len(a); i++ {
  84. if a[i] != b[i] {
  85. return false
  86. }
  87. }
  88. return true
  89. }