判断string类型的编码格式
string为multi-byte 字符串,utf8均为 utf-8 格式的string,二者数据类型一样,但内部编码不一样,以下函数可以判断当前string类型字符串是否为utf-8编码格式。
auto isUTF8 = [](const std::string& str)
{
//判断文件是否为UTF-8编码
int length = str.length();
int i = 0;
while (i < length)
{
if ((str[i] & 0x80) == 0)
{
// 0xxxxxxx,单字节字符,符合 UTF-8 规则
i++;
}
else if ((str[i] & 0xE0) == 0xC0)
{
// 110xxxxx 10xxxxxx,两字节字符,继续判断下一个字节
if (i + 1 >= length || (str[i + 1] & 0xC0) != 0x80)
{
return false;
}
i += 2;
}
else if ((str[i] & 0xF0) == 0xE0)
{
// 1110xxxx 10xxxxxx 10xxxxxx,三字节字符,继续判断下两个字节
if (i + 2 >= length ||
(str[i + 1] & 0xC0) != 0x80 ||
(str[i + 2] & 0xC0) != 0x80)
{
return false;
}
i += 3;
}
else if ((str[i] & 0xF8) == 0xF0)
{
// 11110xxx 10xxxxxx 10xxxxxx 10xxxxxx,四字节字符,继续判断下三个字节
if (i + 3 >= length ||
(str[i + 1] & 0xC0) != 0x80 ||
(str[i + 2] & 0xC0) != 0x80 ||
(str[i + 3] & 0xC0) != 0x80)
{
return false;
}
i += 4;
}
else
{
// 非 UTF-8 编码规则
return false;
}
}
return true;
};