1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889 |
- package stringutil
- import (
- "strings"
- "github.com/mozillazg/go-pinyin"
- )
- // ZhToPinyin 中文转拼音
- func ZhToPinyin(zh, sep string) string {
- args := pinyin.NewArgs()
- p := pinyin.Pinyin(zh, args)
- names := make([]string, 0, len(p))
- for _, v := range p {
- if len(v) > 0 {
- if len(v) == 1 {
- names = append(names, v[0])
- } else {
- names = append(names, strings.Join(v, ""))
- }
- }
- }
- return strings.Join(names, sep)
- }
- type CamelType int
- const (
- CamelSmall CamelType = 1 // a_bc aBc
- CamelBig CamelType = 2 // a_bc ABc
- )
- // CamelToSnake 驼峰转蛇形
- func CamelToSnake(s string) string {
- data := make([]byte, 0, len(s)*2)
- j := false
- num := len(s)
- for i := 0; i < num; i++ {
- d := s[i]
- // or通过ASCII码进行大小写的转化
- // 65-90(A-Z),97-122(a-z)
- // 判断如果字母为大写的A-Z就在前面拼接一个_
- if i > 0 && d >= 'A' && d <= 'Z' && j {
- data = append(data, '_')
- }
- if d != '_' {
- j = true
- }
- data = append(data, d)
- }
- // ToLower把大写字母统一转小写
- return strings.ToLower(string(data[:]))
- }
- // SnakeToCamel 蛇形转驼峰 a_b to AB
- func SnakeToCamel(s string, camel CamelType) string {
- data := make([]byte, 0, len(s))
- j := false
- k := false
- num := len(s) - 1
- for i := 0; i <= num; i++ {
- d := s[i]
- if k == false && d >= 'A' && d <= 'Z' {
- k = true
- }
- if d >= 'a' && d <= 'z' && (j || k == false) {
- d = d - 32
- j = false
- k = true
- }
- if k && d == '_' && num > i && s[i+1] >= 'a' && s[i+1] <= 'z' {
- j = true
- continue
- }
- data = append(data, d)
- }
- str := string(data[:])
- switch camel {
- case CamelSmall:
- return strings.ToLower(str[0:1]) + str[1:]
- case CamelBig:
- return str
- default:
- return str
- }
- }
|