清风细雨楼 Design By www.eepep.com

本文实例讲述了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 ""
}

希望本文所述对大家的Go语言程序设计有所帮助。

清风细雨楼 Design By www.eepep.com
广告合作:本站广告合作请联系QQ:858582 申请时备注:广告合作(否则不回)
免责声明:本站资源来自互联网收集,仅供用于学习和交流,请遵循相关法律法规,本站一切资源不代表本站立场,如有侵权、后门、不妥请联系本站删除!
清风细雨楼 Design By www.eepep.com