string.go 2.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110
  1. package stringx
  2. import (
  3. "bytes"
  4. "strings"
  5. "unicode"
  6. )
  7. type (
  8. String struct {
  9. source string
  10. }
  11. )
  12. func From(data string) String {
  13. return String{source: data}
  14. }
  15. func (s String) IsEmptyOrSpace() bool {
  16. if len(s.source) == 0 {
  17. return true
  18. }
  19. if strings.TrimSpace(s.source) == "" {
  20. return true
  21. }
  22. return false
  23. }
  24. func (s String) Lower() string {
  25. return strings.ToLower(s.source)
  26. }
  27. func (s String) Upper() string {
  28. return strings.ToUpper(s.source)
  29. }
  30. func (s String) Title() string {
  31. if s.IsEmptyOrSpace() {
  32. return s.source
  33. }
  34. return strings.Title(s.source)
  35. }
  36. // snake->camel(upper start)
  37. func (s String) ToCamel() string {
  38. list := s.splitBy(func(r rune) bool {
  39. return r == '_'
  40. }, true)
  41. var target []string
  42. for _, item := range list {
  43. target = append(target, From(item).Title())
  44. }
  45. return strings.Join(target, "")
  46. }
  47. // camel->snake
  48. func (s String) ToSnake() string {
  49. list := s.splitBy(func(r rune) bool {
  50. return unicode.IsUpper(r)
  51. }, false)
  52. var target []string
  53. for _, item := range list {
  54. target = append(target, From(item).Lower())
  55. }
  56. return strings.Join(target, "_")
  57. }
  58. // return original string if rune is not letter at index 0
  59. func (s String) UnTitle() string {
  60. if s.IsEmptyOrSpace() {
  61. return s.source
  62. }
  63. r := rune(s.source[0])
  64. if !unicode.IsUpper(r) && !unicode.IsLower(r) {
  65. return s.source
  66. }
  67. return string(unicode.ToLower(r)) + s.source[1:]
  68. }
  69. // it will not ignore spaces
  70. func (s String) splitBy(fn func(r rune) bool, remove bool) []string {
  71. if s.IsEmptyOrSpace() {
  72. return nil
  73. }
  74. var list []string
  75. buffer := new(bytes.Buffer)
  76. for _, r := range s.source {
  77. if fn(r) {
  78. if buffer.Len() != 0 {
  79. list = append(list, buffer.String())
  80. buffer.Reset()
  81. }
  82. if !remove {
  83. buffer.WriteRune(r)
  84. }
  85. continue
  86. }
  87. buffer.WriteRune(r)
  88. }
  89. if buffer.Len() != 0 {
  90. list = append(list, buffer.String())
  91. }
  92. return list
  93. }
  94. func (s String) ReplaceAll(old, new string) string {
  95. return strings.ReplaceAll(s.source, old, new)
  96. }
  97. func (s String) Source() string {
  98. return s.source
  99. }