字符串处理
空白检查、截断、命名转换、脱敏等字符串工具
字符串处理
xUtil 提供丰富的字符串处理函数,包括空白检查、截断、命名转换、脱敏等。
空白检查
IsBlank
检查字符串是否为空白(空字符串或只包含空白字符):
func IsBlank(str string) boolxUtil.IsBlank("") // true
xUtil.IsBlank(" ") // true
xUtil.IsBlank("\t\n") // true
xUtil.IsBlank("hello") // falseIsNotBlank
检查字符串是否不为空白:
func IsNotBlank(str string) boolxUtil.IsNotBlank("hello") // true
xUtil.IsNotBlank("") // falseDefaultIfBlank
如果字符串为空白则返回默认值:
func DefaultIfBlank(str, defaultStr string) stringxUtil.DefaultIfBlank("", "default") // "default"
xUtil.DefaultIfBlank(" ", "default") // "default"
xUtil.DefaultIfBlank("hello", "default") // "hello"字符串截断
Truncate
截断字符串到指定长度:
func Truncate(str string, maxLen int) stringxUtil.Truncate("Hello World", 5) // "Hello"
xUtil.Truncate("Hi", 10) // "Hi"TruncateWithSuffix
截断字符串并添加后缀:
func TruncateWithSuffix(str string, maxLen int, suffix string) stringxUtil.TruncateWithSuffix("Hello World", 8, "...") // "Hello..."
xUtil.TruncateWithSuffix("Hi", 10, "...") // "Hi"
xUtil.TruncateWithSuffix("Hello", 8, "") // "Hello"(默认后缀 "...")命名转换
CamelToSnake
驼峰命名转蛇形命名:
func CamelToSnake(str string) stringxUtil.CamelToSnake("userName") // "user_name"
xUtil.CamelToSnake("UserName") // "user_name"
xUtil.CamelToSnake("userID") // "user_i_d"
xUtil.CamelToSnake("HTTPServer") // "h_t_t_p_server"SnakeToCamel
蛇形命名转驼峰命名:
func SnakeToCamel(str string) stringxUtil.SnakeToCamel("user_name") // "userName"
xUtil.SnakeToCamel("user_id") // "userId"
xUtil.SnakeToCamel("http_server") // "httpServer"字符串脱敏
MaskString
对字符串进行脱敏处理:
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
检查是否为有效的邮箱地址:
func IsValidEmail(email string) boolxUtil.IsValidEmail("test@example.com") // true
xUtil.IsValidEmail("invalid-email") // falseRemoveSpaces
移除字符串中的所有空格:
func RemoveSpaces(str string) stringxUtil.RemoveSpaces("hello world") // "helloworld"
xUtil.RemoveSpaces(" a b c ") // "abc"CountWords
统计字符串中的单词数量:
func CountWords(str string) intxUtil.CountWords("hello world") // 2
xUtil.CountWords(" hello world ") // 2
xUtil.CountWords("") // 0