string.go 2.0 KB

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