case.go 1.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127
  1. package util
  2. import (
  3. "strings"
  4. "unicode"
  5. )
  6. func IsUpperCase(r rune) bool {
  7. if r >= 'A' && r <= 'Z' {
  8. return true
  9. }
  10. return false
  11. }
  12. func IsLowerCase(r rune) bool {
  13. if r >= 'a' && r <= 'z' {
  14. return true
  15. }
  16. return false
  17. }
  18. func ToSnakeCase(s string) string {
  19. var out []rune
  20. for index, r := range s {
  21. if index == 0 {
  22. out = append(out, ToLowerCase(r))
  23. continue
  24. }
  25. if IsUpperCase(r) && index != 0 {
  26. if IsLowerCase(rune(s[index-1])) {
  27. out = append(out, '_', ToLowerCase(r))
  28. continue
  29. }
  30. if index < len(s)-1 && IsLowerCase(rune(s[index+1])) {
  31. out = append(out, '_', ToLowerCase(r))
  32. continue
  33. }
  34. out = append(out, ToLowerCase(r))
  35. continue
  36. }
  37. out = append(out, r)
  38. }
  39. return string(out)
  40. }
  41. func ToCamelCase(s string) string {
  42. s = ToLower(s)
  43. out := []rune{}
  44. for index, r := range s {
  45. if r == '_' {
  46. continue
  47. }
  48. if index == 0 {
  49. out = append(out, ToUpperCase(r))
  50. continue
  51. }
  52. if index > 0 && s[index-1] == '_' {
  53. out = append(out, ToUpperCase(r))
  54. continue
  55. }
  56. out = append(out, r)
  57. }
  58. return string(out)
  59. }
  60. func ToLowerCase(r rune) rune {
  61. dx := 'A' - 'a'
  62. if IsUpperCase(r) {
  63. return r - dx
  64. }
  65. return r
  66. }
  67. func ToUpperCase(r rune) rune {
  68. dx := 'A' - 'a'
  69. if IsLowerCase(r) {
  70. return r + dx
  71. }
  72. return r
  73. }
  74. func ToLower(s string) string {
  75. var out []rune
  76. for _, r := range s {
  77. out = append(out, ToLowerCase(r))
  78. }
  79. return string(out)
  80. }
  81. func ToUpper(s string) string {
  82. var out []rune
  83. for _, r := range s {
  84. out = append(out, ToUpperCase(r))
  85. }
  86. return string(out)
  87. }
  88. func LowerFirst(s string) string {
  89. if len(s) == 0 {
  90. return s
  91. }
  92. return ToLower(s[:1]) + s[1:]
  93. }
  94. func UpperFirst(s string) string {
  95. if len(s) == 0 {
  96. return s
  97. }
  98. return ToUpper(s[:1]) + s[1:]
  99. }
  100. func UnExport(text string) bool {
  101. var flag bool
  102. str := strings.Map(func(r rune) rune {
  103. if flag {
  104. return r
  105. }
  106. if unicode.IsLetter(r) {
  107. flag = true
  108. return unicode.ToLower(r)
  109. }
  110. return r
  111. }, text)
  112. return str == text
  113. }