本文实例讲述了Go语言按字节截取字符串的方法。分享给大家供大家参考。具体实现方法如下:
复制代码 代码如下:
// 按字节截取字符串 utf-8不乱码
func SubstrByByte(str string, length int) string {
bs := []byte(str)[:length]
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 ""
}
func SubstrByByte(str string, length int) string {
bs := []byte(str)[:length]
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 ""
}
希望本文所述对大家的Go语言程序设计有所帮助。