- LimitUTF8StringLen

This commit is contained in:
gazebo
2019-03-31 12:13:28 +08:00
parent e8c84c3b21
commit ce422881bc
2 changed files with 51 additions and 0 deletions

View File

@@ -246,3 +246,24 @@ func Base64DecodeMultiString(strs ...string) (decodedData [][]byte, err error) {
}
return decodedData, nil
}
func LimitStringLen(str string, maxLen int) (limitedStr string) {
if maxLen > 0 {
if strLen := len(str); strLen > maxLen {
str = str[:maxLen]
}
}
return str
}
func LimitUTF8StringLen(str string, maxLen int) (limitedStr string) {
if maxLen > 0 {
if len(str) > maxLen {
runeList := []rune(str)
if len(runeList) > maxLen {
str = string(runeList[:maxLen])
}
}
}
return str
}

View File

@@ -185,3 +185,33 @@ func TestStruct2MapByJson(t *testing.T) {
})
t.Log(mapData)
}
func TestLimitUTF8StringLen(t *testing.T) {
for _, v := range [][]interface{}{
[]interface{}{
"123456789",
6,
"123456",
},
[]interface{}{
"123456789",
0,
"123456789",
},
[]interface{}{
"一二345六789",
6,
"一二345六",
},
[]interface{}{
"1二345六789",
0,
"1二345六789",
},
} {
str := LimitUTF8StringLen(v[0].(string), v[1].(int))
if str != v[2] {
t.Fatalf("%v处理错误预期:%v实际:%s", v[0], v[2], str)
}
}
}