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.

77 lines
1.6 KiB

9 years ago
  1. package strings
  2. import (
  3. "fmt"
  4. "strings"
  5. )
  6. // StringInSlice returns true if a is found the list.
  7. func StringInSlice(a string, list []string) bool {
  8. for _, b := range list {
  9. if b == a {
  10. return true
  11. }
  12. }
  13. return false
  14. }
  15. // SplitAndTrim slices s into all subslices separated by sep and returns a
  16. // slice of the string s with all leading and trailing Unicode code points
  17. // contained in cutset removed. If sep is empty, SplitAndTrim splits after each
  18. // UTF-8 sequence. First part is equivalent to strings.SplitN with a count of
  19. // -1.
  20. func SplitAndTrim(s, sep, cutset string) []string {
  21. if s == "" {
  22. return []string{}
  23. }
  24. spl := strings.Split(s, sep)
  25. for i := 0; i < len(spl); i++ {
  26. spl[i] = strings.Trim(spl[i], cutset)
  27. }
  28. return spl
  29. }
  30. // Returns true if s is a non-empty printable non-tab ascii character.
  31. func IsASCIIText(s string) bool {
  32. if len(s) == 0 {
  33. return false
  34. }
  35. for _, b := range []byte(s) {
  36. if 32 <= b && b <= 126 {
  37. // good
  38. } else {
  39. return false
  40. }
  41. }
  42. return true
  43. }
  44. // NOTE: Assumes that s is ASCII as per IsASCIIText(), otherwise panics.
  45. func ASCIITrim(s string) string {
  46. r := make([]byte, 0, len(s))
  47. for _, b := range []byte(s) {
  48. switch {
  49. case b == 32:
  50. continue // skip space
  51. case 32 < b && b <= 126:
  52. r = append(r, b)
  53. default:
  54. panic(fmt.Sprintf("non-ASCII (non-tab) char 0x%X", b))
  55. }
  56. }
  57. return string(r)
  58. }
  59. // StringSliceEqual checks if string slices a and b are equal
  60. func StringSliceEqual(a, b []string) bool {
  61. if len(a) != len(b) {
  62. return false
  63. }
  64. for i := 0; i < len(a); i++ {
  65. if a[i] != b[i] {
  66. return false
  67. }
  68. }
  69. return true
  70. }