最新国产好看的视频,伊人天堂AV在线,国产Aaaaaa视频,蜜臀视频在线观看一区,人妻av色图,密臀久久久精品影片,青青视频免费观看毛片,久草在线观看视,国产三级精品色情在线

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

 更新時間:2014年08月05日 09:55:20   投稿:junjie  
這篇文章主要介紹了C++中可正確獲取UTF-8字符長度的函數(shù)分享,需要的朋友可以參考下

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

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

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

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

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

可以改造出下面的函數(shù):

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;
}

相關文章

最新評論

任丘市| 石嘴山市| 南阳市| 木里| 正安县| 嘉禾县| 德阳市| 永寿县| 德阳市| 长子县| 长汀县| 中西区| 张家口市| 布尔津县| 德州市| 保亭| 庐江县| 津市市| 连平县| 丰镇市| 定远县| 柳林县| 鱼台县| 萨迦县| 永胜县| 绥棱县| 汽车| 霍州市| 和田县| 南宁市| 富裕县| 县级市| 万山特区| 方城县| 张北县| 汉中市| 宣化县| 浏阳市| 满城县| 萍乡市| 蒲城县|