feat: 增加 str snake and camel 函数
This commit is contained in:
parent
7853a35d99
commit
9742dccdfa
@ -9,11 +9,12 @@ package helper
|
||||
|
||||
import (
|
||||
"math/rand"
|
||||
"strings"
|
||||
"time"
|
||||
"unicode"
|
||||
|
||||
"github.com/rs/xid"
|
||||
"git.hexq.cn/tiglog/golib/crypto/gmd5"
|
||||
"github.com/rs/xid"
|
||||
)
|
||||
|
||||
// 是否是字符串
|
||||
@ -51,6 +52,49 @@ func LcFirst(str string) string {
|
||||
return ""
|
||||
}
|
||||
|
||||
// 驼峰转蛇形, XxYy => xx_yy
|
||||
func SnakeString(str string) string {
|
||||
data := make([]byte, 0, len(str)*2)
|
||||
j := false
|
||||
num := len(str)
|
||||
for i := 0; i < num; i++ {
|
||||
d := str[i]
|
||||
if i > 0 && d >= 'A' && d <= 'Z' && j {
|
||||
data = append(data, '_')
|
||||
}
|
||||
if d != '_' {
|
||||
j = true
|
||||
}
|
||||
data = append(data, d)
|
||||
}
|
||||
return strings.ToLower(string(data[:]))
|
||||
}
|
||||
|
||||
// 蛇形转驼峰, xx_yy => XxYy
|
||||
func CamelString(str string) string {
|
||||
data := make([]byte, 0, len(str))
|
||||
j := false
|
||||
k := false
|
||||
num := len(str) - 1
|
||||
for i := 0; i <= num; i++ {
|
||||
d := str[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 && str[i+1] >= 'a' && str[i+1] <= 'z' {
|
||||
j = true
|
||||
continue
|
||||
}
|
||||
data = append(data, d)
|
||||
}
|
||||
return string(data[:])
|
||||
}
|
||||
|
||||
// 乱序字符串
|
||||
func Shuffle(str string) string {
|
||||
if str == "" {
|
||||
|
@ -118,3 +118,15 @@ func TestUniq(t *testing.T) {
|
||||
gtest.NotNil(t, s90)
|
||||
// fmt.Println(s60, s70, s80, s90)
|
||||
}
|
||||
|
||||
func TestSnake(t *testing.T) {
|
||||
s1 := "XxYy"
|
||||
r1 := helper.SnakeString(s1)
|
||||
gtest.Equal(t, "xx_yy", r1)
|
||||
}
|
||||
|
||||
func TestCamel(t *testing.T) {
|
||||
s1 := "xx_yy"
|
||||
r1 := helper.CamelString(s1)
|
||||
gtest.Equal(t, "XxYy", r1)
|
||||
}
|
||||
|
Loading…
Reference in New Issue
Block a user