在日常 Go 开发中,字符串处理是高频操作:分割、裁剪、替换、拼接......如果每次都去写重复逻辑,不仅麻烦,还容易出错。
这时就可以用开源工具库 go-commons,它为我们封装了常用的字符串处理方法,写法简洁、功能丰富。
一、安装 go-commons
直接通过 go get
拉取依赖:
bash
go get github.com/Rodert/go-commons
在代码里引入:
go
import "github.com/Rodert/go-commons/strutil"
二、常见字符串操作示例
下面通过一个完整的 demo 展示 裁剪、分割、替换、拼接、格式化 等常见功能。
go
package main
import (
"fmt"
"strings"
"github.com/Rodert/go-commons/strutil"
)
func main() {
// 1. 去除首尾空格
raw := " Hello, Go Commons! "
fmt.Println("原始:", raw)
fmt.Println("TrimSpace:", strutil.TrimSpace(raw)) // "Hello, Go Commons!"
// 2. 判断是否为空
empty := " "
fmt.Println("IsBlank(empty):", strutil.IsBlank(empty)) // true
// 3. 分割字符串
data := "apple,banana,orange,,pear"
parts := strutil.Split(data, ",")
fmt.Println("Split:", parts) // [apple banana orange pear]
// 4. 安全获取数组中的值
fmt.Println("GetOrDefault:", strutil.GetOrDefault(parts, 2, "default")) // orange
fmt.Println("GetOrDefault:", strutil.GetOrDefault(parts, 10, "default")) // default
// 5. 替换敏感信息(脱敏)
phone := "13812345678"
fmt.Println("MaskMobile:", strutil.MaskMobile(phone)) // 138****5678
// 6. 拼接字符串
list := []string{"go", "commons", "rocks"}
fmt.Println("Join:", strutil.Join(list, "-")) // go-commons-rocks
// 7. 大小写处理
text := "hello WORLD"
fmt.Println("UpperFirst:", strutil.UpperFirst(text)) // Hello WORLD
fmt.Println("LowerFirst:", strutil.LowerFirst(text)) // hello WORLD
// 8. 驼峰 & 下划线互转
camel := "user_name_id"
fmt.Println("ToCamel:", strutil.ToCamel(camel)) // UserNameId
snake := "UserNameId"
fmt.Println("ToSnake:", strutil.ToSnake(snake)) // user_name_id
// 9. 模糊匹配
haystack := "golang is awesome"
fmt.Println("ContainsAny:", strutil.ContainsAny(haystack, []string{"java", "go"})) // true
fmt.Println("ContainsIgnoreCase:", strutil.ContainsIgnoreCase(haystack, "GOLANG")) // true
// 10. 多重替换
text2 := "foo bar baz"
replacer := map[string]string{
"foo": "one",
"bar": "two",
"baz": "three",
}
fmt.Println("ReplaceAll:", strutil.ReplaceAll(text2, replacer)) // one two three
// 11. 去重、过滤空字符串
arr := []string{"go", "commons", "", "go", "commons"}
fmt.Println("Unique:", strutil.Unique(arr)) // [go commons]
// 12. 快速生成重复字符串
fmt.Println("Repeat:", strutil.Repeat("ha", 3)) // hahaha
// 13. 截断字符串
longText := "HelloGopherWorld"
fmt.Println("Substr(0,5):", strutil.Substr(longText, 0, 5)) // Hello
fmt.Println("Substr(5,6):", strutil.Substr(longText, 5, 6)) // Gopher
fmt.Println("Substr(-5,5):", strutil.Substr(longText, -5, 5)) // rWorld
}
三、运行效果
运行上述代码,输出示例(部分):
原始: Hello, Go Commons!
TrimSpace: Hello, Go Commons!
IsBlank(empty): true
Split: [apple banana orange pear]
MaskMobile: 138****5678
Join: go-commons-rocks
ToCamel: UserNameId
ToSnake: user_name_id
ContainsAny: true
ReplaceAll: one two three
Unique: [go commons]
Repeat: hahaha
Substr(0,5): Hello
四、总结
相比自己手写 strings
、regexp
的各种逻辑,
go-commons
提供了一套更 语义化 、安全 的工具函数:
- ✅ 常用功能开箱即用
- ✅ 更安全的边界处理(避免 panic)
- ✅ 支持驼峰/下划线、脱敏、过滤、去重等高级功能
如果你在写 Go 项目,经常需要字符串处理,可以直接引入 go-commons
,让代码更简洁可读。