c语言 定义utf8字符串长度,C++中可正确获取UTF-8字符长度的函数分享

在C++的char*以及string中,使用的是字节流编码,即sizeof(char) == 1。

也就是说,C++是不区分字符的编码的。

而一个合法UTF8的字符长度可能为1~4位。

现在假设一串输入为UTF8编码,如何能准确的定位到每个UTF8字符的“CharPoint”,而不会错误的分割字符呢?

可以改造出下面的函数:

const unsigned char kFirstBitMask = 128; // 1000000

const unsigned char kSecondBitMask = 64; // 0100000

const unsigned char kThirdBitMask = 32; // 0010000

const unsigned char kFourthBitMask = 16; // 0001000

const unsigned char kFifthBitMask = 8; // 0000100

int utf8_char_len(char firstByte)

{

std::string::difference_type offset = 1;

if(firstByte & kFirstBitMask) // This means the first byte has a value greater than 127, and so is beyond the ASCII range.

{

if(firstByte & kThirdBitMask) // This means that the first byte has a value greater than 224, and so it must be at least a three-octet code point.

{

if(firstByte & kFourthBitMask) // This means that the first byte has a value greater than 240, and so it must be a four-octet code point.

offset = 4;

else

offset = 3;

}

else

{

offset = 2;

}

}

return offset;

}

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值