雷火电竞-中国电竞赛事及体育赛事平台

歡迎來到入門教程網(wǎng)!

C語言

當(dāng)前位置:主頁 > 軟件編程 > C語言 >

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

來源:本站原創(chuàng)|時間:2020-01-10|欄目:C語言|點(diǎn)擊:

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

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

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

現(xiàn)在假設(shè)一串輸入為UTF8編碼,如何能準(zhǔn)確的定位到每個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;
}

上一篇:VC程序設(shè)計中CreateProcess用法注意事項(xiàng)

欄    目:C語言

下一篇:VC動態(tài)生成菜單項(xiàng)的實(shí)現(xiàn)方法

本文標(biāo)題:C++中可正確獲取UTF-8字符長度的函數(shù)分享

本文地址:http://www.jygsgssxh.com/a1/Cyuyan/3545.html

網(wǎng)頁制作CMS教程網(wǎng)絡(luò)編程軟件編程腳本語言數(shù)據(jù)庫服務(wù)器

如果侵犯了您的權(quán)利,請與我們聯(lián)系,我們將在24小時內(nèi)進(jìn)行處理、任何非本站因素導(dǎo)致的法律后果,本站均不負(fù)任何責(zé)任。

聯(lián)系QQ:835971066 | 郵箱:835971066#qq.com(#換成@)

Copyright © 2002-2020 腳本教程網(wǎng) 版權(quán)所有