个人技术分享

在go语言的开发中,字符串的处理是最为频繁的, 今天给大家介绍的这个 go-str-utils 专门的字符串处理实用函数库中的 字符串命名转换 大小驼峰, snake, kebab命名转换。

各种命名转换规则和示例

  • CamelStr 大驼峰 单词全部首字母大写 如: UserName

  • SmallCamelStr 小驼峰 第一个单词首字母小写,其他大写, 如: userName

  • SnakeStr 单词全部小写,使用下划线链接, 如: user_name

  • KebabStr 单词全部小写,使用 中划线链接 如: user-name

使用示例

  • 安装最新版本依赖
go get -u github.com/tekintian/go-str-utils
  • 使用示例
import (
	"fmt"
	strutils "github.com/tekintian/go-str-utils"
)

func main() {
  camelStr := strutils.CamelStr("hello-world")
  fmt.Println(camelStr) // 输出: HelloWorld
}

其他使用示例可参考 *_test.go 中的测试用例, 我们的每个函数都有测试用例, 部分函数还使用了 Fuzz 模糊测试技术 来确保我们函数的可靠和高效! 同时也能帮助我们发现一些潜在的风险等......

也可参考 go pkg 文档,地址: strutils package - github.com/tekintian/go-str-utils - Go Packages

字符串命名转换单元测试用例


import (
	"fmt"
	"testing"

	strutils "github.com/tekintian/go-str-utils"
)

func TestStrFn(t *testing.T) {

	cases := []struct {
		fn       func(string) string
		param1   string
		expected string
	}{ // 测试用例数据
		{fn: strutils.CamelStr, param1: "hello_world", expected: "HelloWorld"},
		{fn: strutils.CamelStr, param1: "hello          world    hi Xyz", expected: "HelloWorldHiXyz"},
		{fn: strutils.CamelStr, param1: "hello world你好", expected: "HelloWorld你好"},
		{fn: strutils.SmallCamelStr, param1: "hello-world", expected: "helloWorld"},
		{fn: strutils.SnakeStr, param1: "helloWorld", expected: "hello_world"},
		{fn: strutils.KebabStr, param1: "HelloWorld", expected: "hello-world"},
		{fn: strutils.Html2str, param1: "<b>hello world</b>\n\n\n\n<script>< / b>", expected: "hello world"},
		{fn: strutils.UcWords, param1: "hello world-How_are-you", expected: "Hello World How Are You"},
		{fn: strutils.UcWords, param1: "hello_world", expected: "Hello World"},
		{fn: strutils.UcWords, param1: "hello 你好 XYZ", expected: "Hello 你好 XYZ"},
		{fn: strutils.UcFirst, param1: "hello world", expected: "Hello world"},
		{fn: strutils.LcFirst, param1: "Hello World", expected: "hello World"},
	}

	for _, c := range cases {
		fname := fmt.Sprintf("%p", c.fn)
		t.Run(fname, func(t *testing.T) {
			x := c.fn(c.param1)
			if x != c.expected {
				t.Fatalf("%v Expected %v, got %v", fname, c.expected, x)
			}
		})
	}
}

Github仓库地址 GitHub - tekintian/go-str-utils: go语言里面高效,符合使用习惯的字符串相关的实用工具函数 The effective, idiomatic golang utils for go string

Go Pkg文档地址 strutils package - github.com/tekintian/go-str-utils - Go Packages