C++中可正确获取UTF-8字符长度的函数分享
在C++的char*以及string中,使用的是字节流编码,即sizeof(char)==1。
也就是说,C++是不区分字符的编码的。
而一个合法UTF8的字符长度可能为1~4位。
现在假设一串输入为UTF8编码,如何能准确的定位到每个UTF8字符的“CharPoint”,而不会错误的分割字符呢?
参考这个页面:http://www.nubaria.com/en/blog/?p=289
可以改造出下面的函数:
constunsignedcharkFirstBitMask=128;//1000000
constunsignedcharkSecondBitMask=64;//0100000
constunsignedcharkThirdBitMask=32;//0010000
constunsignedcharkFourthBitMask=16;//0001000
constunsignedcharkFifthBitMask=8;//0000100
intutf8_char_len(charfirstByte)
{
std::string::difference_typeoffset=1;
if(firstByte&kFirstBitMask)//Thismeansthefirstbytehasavaluegreaterthan127,andsoisbeyondtheASCIIrange.
{
if(firstByte&kThirdBitMask)//Thismeansthatthefirstbytehasavaluegreaterthan224,andsoitmustbeatleastathree-octetcodepoint.
{
if(firstByte&kFourthBitMask)//Thismeansthatthefirstbytehasavaluegreaterthan240,andsoitmustbeafour-octetcodepoint.
offset=4;
else
offset=3;
}
else
{
offset=2;
}
}
returnoffset;
}
热门推荐
1 训练狗狗憋尿
2 狗狗追踪训练
3 狗狗训练要多少钱
5 深圳狗狗训练
6 训练狗狗唤回
7 狗狗叫怎么训练
8 狗狗训练班
10 狗狗社会化训练
11 狗狗叫回训练
12 广州狗狗训练学校
13 狗狗训练躺下
14 狗狗随行训练
15 训练狗狗巡回
16 狗狗要怎么训练
17 狗狗喂食训练
18 训练狗狗躺下