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)在假設(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; }
相關(guān)文章
使用udp發(fā)送>=128K的消息會報ENOBUFS的錯誤的解決方法
在項目中選擇了unix域的數(shù)據(jù)報套接口。在使用過程中碰到了如下,問題:發(fā)送<128K的消息時,客戶、進程可以正常收發(fā)消息;發(fā)送>=128K的消息時,發(fā)送端(sendto)返回ENOBUFS的錯誤。下面小編來詳細說下2019-05-05