竹简文档

字符串处理

空白检查、截断、命名转换、脱敏等字符串工具

字符串处理

xUtil 提供丰富的字符串处理函数,包括空白检查、截断、命名转换、脱敏等。

空白检查

IsBlank

检查字符串是否为空白(空字符串或只包含空白字符):

string.go
func IsBlank(str string) bool
xUtil.IsBlank("")          // true
xUtil.IsBlank("  ")        // true
xUtil.IsBlank("\t\n")      // true
xUtil.IsBlank("hello")     // false

IsNotBlank

检查字符串是否不为空白:

string.go
func IsNotBlank(str string) bool
xUtil.IsNotBlank("hello")  // true
xUtil.IsNotBlank("")       // false

DefaultIfBlank

如果字符串为空白则返回默认值:

string.go
func DefaultIfBlank(str, defaultStr string) string
xUtil.DefaultIfBlank("", "default")      // "default"
xUtil.DefaultIfBlank("  ", "default")    // "default"
xUtil.DefaultIfBlank("hello", "default") // "hello"

字符串截断

Truncate

截断字符串到指定长度:

string.go
func Truncate(str string, maxLen int) string
xUtil.Truncate("Hello World", 5)   // "Hello"
xUtil.Truncate("Hi", 10)           // "Hi"

TruncateWithSuffix

截断字符串并添加后缀:

string.go
func TruncateWithSuffix(str string, maxLen int, suffix string) string
xUtil.TruncateWithSuffix("Hello World", 8, "...")   // "Hello..."
xUtil.TruncateWithSuffix("Hi", 10, "...")           // "Hi"
xUtil.TruncateWithSuffix("Hello", 8, "")            // "Hello"(默认后缀 "...")

命名转换

CamelToSnake

驼峰命名转蛇形命名:

string.go
func CamelToSnake(str string) string
xUtil.CamelToSnake("userName")       // "user_name"
xUtil.CamelToSnake("UserName")       // "user_name"
xUtil.CamelToSnake("userID")         // "user_i_d"
xUtil.CamelToSnake("HTTPServer")     // "h_t_t_p_server"

SnakeToCamel

蛇形命名转驼峰命名:

string.go
func SnakeToCamel(str string) string
xUtil.SnakeToCamel("user_name")      // "userName"
xUtil.SnakeToCamel("user_id")        // "userId"
xUtil.SnakeToCamel("http_server")    // "httpServer"

字符串脱敏

MaskString

对字符串进行脱敏处理:

string.go
func MaskString(str string, start, end int, mask string) string

参数说明:

字段

类型

示例:

// 手机号脱敏
xUtil.MaskString("13812345678", 3, 4, "*")   // "138****5678"

// 身份证脱敏
xUtil.MaskString("110101199001011234", 6, 4, "*")  // "110101********1234"

// 邮箱脱敏
xUtil.MaskString("test@example.com", 2, 4, "*")   // "te**********m.com"

// 短字符串(长度不足时全部脱敏)
xUtil.MaskString("abc", 3, 4, "*")           // "***"

其他工具

IsValidEmail

检查是否为有效的邮箱地址:

string.go
func IsValidEmail(email string) bool
xUtil.IsValidEmail("test@example.com")   // true
xUtil.IsValidEmail("invalid-email")      // false

RemoveSpaces

移除字符串中的所有空格:

string.go
func RemoveSpaces(str string) string
xUtil.RemoveSpaces("hello world")        // "helloworld"
xUtil.RemoveSpaces("  a  b  c  ")        // "abc"

CountWords

统计字符串中的单词数量:

string.go
func CountWords(str string) int
xUtil.CountWords("hello world")          // 2
xUtil.CountWords("  hello   world  ")    // 2
xUtil.CountWords("")                     // 0

下一步

On this page