pinyin.go 1.7 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889
  1. package stringutil
  2. import (
  3. "strings"
  4. "github.com/mozillazg/go-pinyin"
  5. )
  6. // ZhToPinyin 中文转拼音
  7. func ZhToPinyin(zh, sep string) string {
  8. args := pinyin.NewArgs()
  9. p := pinyin.Pinyin(zh, args)
  10. names := make([]string, 0, len(p))
  11. for _, v := range p {
  12. if len(v) > 0 {
  13. if len(v) == 1 {
  14. names = append(names, v[0])
  15. } else {
  16. names = append(names, strings.Join(v, ""))
  17. }
  18. }
  19. }
  20. return strings.Join(names, sep)
  21. }
  22. type CamelType int
  23. const (
  24. CamelSmall CamelType = 1 // a_bc aBc
  25. CamelBig CamelType = 2 // a_bc ABc
  26. )
  27. // CamelToSnake 驼峰转蛇形
  28. func CamelToSnake(s string) string {
  29. data := make([]byte, 0, len(s)*2)
  30. j := false
  31. num := len(s)
  32. for i := 0; i < num; i++ {
  33. d := s[i]
  34. // or通过ASCII码进行大小写的转化
  35. // 65-90(A-Z),97-122(a-z)
  36. // 判断如果字母为大写的A-Z就在前面拼接一个_
  37. if i > 0 && d >= 'A' && d <= 'Z' && j {
  38. data = append(data, '_')
  39. }
  40. if d != '_' {
  41. j = true
  42. }
  43. data = append(data, d)
  44. }
  45. // ToLower把大写字母统一转小写
  46. return strings.ToLower(string(data[:]))
  47. }
  48. // SnakeToCamel 蛇形转驼峰 a_b to AB
  49. func SnakeToCamel(s string, camel CamelType) string {
  50. data := make([]byte, 0, len(s))
  51. j := false
  52. k := false
  53. num := len(s) - 1
  54. for i := 0; i <= num; i++ {
  55. d := s[i]
  56. if k == false && d >= 'A' && d <= 'Z' {
  57. k = true
  58. }
  59. if d >= 'a' && d <= 'z' && (j || k == false) {
  60. d = d - 32
  61. j = false
  62. k = true
  63. }
  64. if k && d == '_' && num > i && s[i+1] >= 'a' && s[i+1] <= 'z' {
  65. j = true
  66. continue
  67. }
  68. data = append(data, d)
  69. }
  70. str := string(data[:])
  71. switch camel {
  72. case CamelSmall:
  73. return strings.ToLower(str[0:1]) + str[1:]
  74. case CamelBig:
  75. return str
  76. default:
  77. return str
  78. }
  79. }