-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathschema.go
59 lines (55 loc) · 1.26 KB
/
schema.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
/*
* @Author: dongzhzheng
* @Date: 2020-09-04 11:57:11
* @LastEditTime: 2020-12-29 20:33:13
* @LastEditors: dongzhzheng
* @FilePath: /go-utils/schema.go
* @Description: 名字风格转换 驼峰蛇形互转
*/
package utils
import "strings"
// SnakeString 驼峰转蛇形
func SnakeString(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 && s[i-1] >= 'a' && s[i-1] <= 'z' {
data = append(data, '_')
}
if d != '_' {
j = true
}
data = append(data, d)
}
//ToLower把大写字母统一转小写
return strings.ToLower(string(data[:]))
}
// CamelString 蛇形转驼峰
func CamelString(s string) 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 && d >= 'A' && d <= 'Z' {
k = true
}
if d >= 'a' && d <= 'z' && (j || !k) {
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)
}
return string(data[:])
}