C語言中判斷一個char*是不是utf8編碼。本站提示廣大學習愛好者:(C語言中判斷一個char*是不是utf8編碼)文章只能為提供參考,不一定能成為您想要的結果。以下是C語言中判斷一個char*是不是utf8編碼正文
投稿:lqh
這篇文章主要介紹了C語言中判斷一個char*是不是utf8編碼的相關資料,需要的朋友可以參考下C語言中判斷一個char*是不是utf8編碼
裡我修改了一下, 純ASCII編碼的字符串也返回true, 因為UTF8和ASCII兼容
實例代碼:
int utf8_check(const char* str, size_t length) {
size_t i;
int nBytes;
unsigned char chr;
i = 0;
nBytes = 0;
while (i < length) {
chr = *(str + i);
if (nBytes == 0) { //計算字節數
if ((chr & 0x80) != 0) {
while ((chr & 0x80) != 0) {
chr <<= 1;
nBytes++;
}
if ((nBytes < 2) || (nBytes > 6)) {
return 0; //第一個字節最少為110x xxxx
}
nBytes--; //減去自身占的一個字節
}
} else { //多字節除了第一個字節外剩下的字節
if ((chr & 0xC0) != 0x80) {
return 0; //剩下的字節都是10xx xxxx的形式
}
nBytes--;
}
i++;
}
return (nBytes == 0);
}
感謝閱讀,希望能幫助到大家,謝謝大家對本站的支持!