strings.go 2.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131
  1. package stringx
  2. import (
  3. "errors"
  4. "github.com/tal-tech/go-zero/core/lang"
  5. )
  6. var (
  7. ErrInvalidStartPosition = errors.New("start position is invalid")
  8. ErrInvalidStopPosition = errors.New("stop position is invalid")
  9. )
  10. func Contains(list []string, str string) bool {
  11. for _, each := range list {
  12. if each == str {
  13. return true
  14. }
  15. }
  16. return false
  17. }
  18. func Filter(s string, filter func(r rune) bool) string {
  19. var n int
  20. chars := []rune(s)
  21. for i, x := range chars {
  22. if n < i {
  23. chars[n] = x
  24. }
  25. if !filter(x) {
  26. n++
  27. }
  28. }
  29. return string(chars[:n])
  30. }
  31. func HasEmpty(args ...string) bool {
  32. for _, arg := range args {
  33. if len(arg) == 0 {
  34. return true
  35. }
  36. }
  37. return false
  38. }
  39. func NotEmpty(args ...string) bool {
  40. return !HasEmpty(args...)
  41. }
  42. func Remove(strings []string, strs ...string) []string {
  43. out := append([]string(nil), strings...)
  44. for _, str := range strs {
  45. var n int
  46. for _, v := range out {
  47. if v != str {
  48. out[n] = v
  49. n++
  50. }
  51. }
  52. out = out[:n]
  53. }
  54. return out
  55. }
  56. func Reverse(s string) string {
  57. runes := []rune(s)
  58. for from, to := 0, len(runes)-1; from < to; from, to = from+1, to-1 {
  59. runes[from], runes[to] = runes[to], runes[from]
  60. }
  61. return string(runes)
  62. }
  63. // Substr returns runes between start and stop [start, stop) regardless of the chars are ascii or utf8
  64. func Substr(str string, start int, stop int) (string, error) {
  65. rs := []rune(str)
  66. length := len(rs)
  67. if start < 0 || start > length {
  68. return "", ErrInvalidStartPosition
  69. }
  70. if stop < 0 || stop > length {
  71. return "", ErrInvalidStopPosition
  72. }
  73. return string(rs[start:stop]), nil
  74. }
  75. func TakeOne(valid, or string) string {
  76. if len(valid) > 0 {
  77. return valid
  78. }
  79. return or
  80. }
  81. func TakeWithPriority(fns ...func() string) string {
  82. for _, fn := range fns {
  83. val := fn()
  84. if len(val) > 0 {
  85. return val
  86. }
  87. }
  88. return ""
  89. }
  90. func Union(first, second []string) []string {
  91. set := make(map[string]lang.PlaceholderType)
  92. for _, each := range first {
  93. set[each] = lang.Placeholder
  94. }
  95. for _, each := range second {
  96. set[each] = lang.Placeholder
  97. }
  98. merged := make([]string, 0, len(set))
  99. for k := range set {
  100. merged = append(merged, k)
  101. }
  102. return merged
  103. }