国产探花免费观看_亚洲丰满少妇自慰呻吟_97日韩有码在线_资源在线日韩欧美_一区二区精品毛片,辰东完美世界有声小说,欢乐颂第一季,yy玄幻小说排行榜完本

首頁 > 編程 > C++ > 正文

C++中可正確獲取UTF-8字符長度的函數分享

2020-05-23 14:22:23
字體:
來源:轉載
供稿:網友
這篇文章主要介紹了C++中可正確獲取UTF-8字符長度的函數分享,需要的朋友可以參考下
 
 

在C++的char*以及string中,使用的是字節流編碼,即sizeof(char) == 1。

也就是說,C++是不區分字符的編碼的。

而一個合法UTF8的字符長度可能為1~4位。

現在假設一串輸入為UTF8編碼,如何能準確的定位到每個UTF8字符的“CharPoint”,而不會錯誤的分割字符呢?

參考這個頁面:http://www.nubaria.com/en/blog/?p=289

可以改造出下面的函數:

const unsigned char kFirstBitMask = 128; // 1000000const unsigned char kSecondBitMask = 64; // 0100000const unsigned char kThirdBitMask = 32; // 0010000const unsigned char kFourthBitMask = 16; // 0001000const 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;}

發表評論 共有條評論
用戶名: 密碼:
驗證碼: 匿名發表
主站蜘蛛池模板: 阜城县| 平昌县| 聂拉木县| 庆云县| 苍南县| 岳西县| 济源市| 林口县| 黄陵县| 巴南区| 淮阳县| 城固县| 西宁市| 平安县| 安仁县| 隆安县| 汕尾市| 自治县| 姚安县| 资阳市| 商都县| 涞水县| 铜川市| 安图县| 高州市| 汽车| 额敏县| 巴塘县| 班玛县| 石楼县| 宣威市| 芷江| 淮南市| 嫩江县| 固安县| 离岛区| 会东县| 万盛区| 资阳市| 白玉县| 铜梁县|