- LimitMixedStringLen
This commit is contained in:
@@ -238,23 +238,65 @@ 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]
|
||||
// 只适合与纯英文的情况
|
||||
func LimitStringLen(str string, maxByteCount int) (limitedStr string) {
|
||||
if maxByteCount > 0 {
|
||||
if strLen := len(str); strLen > maxByteCount {
|
||||
str = str[:maxByteCount]
|
||||
}
|
||||
}
|
||||
return str
|
||||
}
|
||||
|
||||
func LimitUTF8StringLen(str string, maxLen int) (limitedStr string) {
|
||||
if maxLen > 0 {
|
||||
if len(str) > maxLen {
|
||||
// 限制的是字符数,不是字节数
|
||||
func LimitUTF8StringLen(str string, maxRuneCount int) (limitedStr string) {
|
||||
if maxRuneCount > 0 {
|
||||
if len(str) > maxRuneCount {
|
||||
runeList := []rune(str)
|
||||
if len(runeList) > maxLen {
|
||||
str = string(runeList[:maxLen])
|
||||
if len(runeList) > maxRuneCount {
|
||||
str = string(runeList[:maxRuneCount])
|
||||
}
|
||||
}
|
||||
}
|
||||
return str
|
||||
}
|
||||
|
||||
// 限制的是字节数,正常处理乱码
|
||||
func LimitMixedStringLen(str string, maxByteCount int) (limitedStr string) {
|
||||
if maxByteCount <= 0 {
|
||||
return str
|
||||
}
|
||||
length := len(str)
|
||||
if maxByteCount >= length {
|
||||
return str
|
||||
}
|
||||
bs := []byte(str)[:maxByteCount]
|
||||
bl := 0
|
||||
for i := len(bs) - 1; i >= 0; i-- {
|
||||
switch {
|
||||
case bs[i] >= 0 && bs[i] <= 127:
|
||||
return string(bs[:i+1])
|
||||
case bs[i] >= 128 && bs[i] <= 191:
|
||||
bl++
|
||||
case bs[i] >= 192 && bs[i] <= 253:
|
||||
cl := 0
|
||||
switch {
|
||||
case bs[i]&252 == 252:
|
||||
cl = 6
|
||||
case bs[i]&248 == 248:
|
||||
cl = 5
|
||||
case bs[i]&240 == 240:
|
||||
cl = 4
|
||||
case bs[i]&224 == 224:
|
||||
cl = 3
|
||||
default:
|
||||
cl = 2
|
||||
}
|
||||
if bl+1 == cl {
|
||||
return string(bs[:i+cl])
|
||||
}
|
||||
return string(bs[:i])
|
||||
}
|
||||
}
|
||||
return ""
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user