diff --git a/helper/str_helper.go b/helper/str_helper.go index 8d63523..eeb0773 100644 --- a/helper/str_helper.go +++ b/helper/str_helper.go @@ -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 == "" { diff --git a/helper/str_helper_test.go b/helper/str_helper_test.go index 3908917..5df5b4f 100644 --- a/helper/str_helper_test.go +++ b/helper/str_helper_test.go @@ -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) +}