搜索与平台和第三方库无关的迭代UTF-8字符串或将其拆分为UTF-8符号数组的方法。
请发布代码段。
解决: C++ iterate or split UTF-8 string into array of symbols?
答案 0 :(得分:27)
如果我理解正确,听起来你想要找到每个UTF-8字符的开头。如果是这样,那么解析它们就相当简单(解释它们是另一回事)。但RFC:
明确定义了涉及多少八位字节的定义Char. number range | UTF-8 octet sequence
(hexadecimal) | (binary)
--------------------+---------------------------------------------
0000 0000-0000 007F | 0xxxxxxx
0000 0080-0000 07FF | 110xxxxx 10xxxxxx
0000 0800-0000 FFFF | 1110xxxx 10xxxxxx 10xxxxxx
0001 0000-0010 FFFF | 11110xxx 10xxxxxx 10xxxxxx 10xxxxxx
例如,如果lb
具有UTF-8字符的第一个八位字节,我认为以下内容将决定所涉及的八位字节数。
unsigned char lb;
if (( lb & 0x80 ) == 0 ) // lead bit is zero, must be a single ascii
printf( "1 octet\n" );
else if (( lb & 0xE0 ) == 0xC0 ) // 110x xxxx
printf( "2 octets\n" );
else if (( lb & 0xF0 ) == 0xE0 ) // 1110 xxxx
printf( "3 octets\n" );
else if (( lb & 0xF8 ) == 0xF0 ) // 1111 0xxx
printf( "4 octets\n" );
else
printf( "Unrecognized lead byte (%02x)\n", lb );
但最终,如果在另一篇文章中建议您使用现有库会更好。上面的代码可能会根据八位字节对字符进行分类,但是一旦完成,它就无法帮助它们做任何事情。
答案 1 :(得分:12)
使用与平台无关的小型UTF8 CPP库解决:
char* str = (char*)text.c_str(); // utf-8 string
char* str_i = str; // string iterator
char* end = str+strlen(str)+1; // end iterator
unsigned char[5] symbol = {0,0,0,0,0};
do
{
uint32_t code = utf8::next(str_i, end); // get 32 bit code of a utf-8 symbol
if (code == 0)
continue;
utf8::append(code, symbol); // initialize array `symbol`
}
while ( str_i < end );
答案 2 :(得分:2)
UTF8 CPP正是您想要的
答案 3 :(得分:1)
尝试ICU Library。
答案 4 :(得分:0)
脱下袖口:
// Return length of s converted. On success return should equal s.length().
// On error return points to the character where decoding failed.
// Remember to check the success flag since decoding errors could occur at
// the end of the string
int convert(std::vector<int>& u, const std::string& s, bool& success) {
success = false;
int cp = 0;
int runlen = 0;
for (std::string::const_iterator it = s.begin(), end = s.end(); it != end; ++it) {
int ch = static_cast<unsigned char>(*it);
if (runlen > 0) {
if ((ch & 0xc0 != 0x80) || cp == 0) return it-s.begin();
cp = (cp << 6) + (ch & 0x3f);
if (--runlen == 0) {
u.push_back(cp);
cp = 0;
}
}
else if (cp == 0) {
if (ch < 0x80) { u.push_back(ch); }
else if (ch > 0xf8) return it-s.begin();
else if (ch > 0xf0) { cp = ch & 7; runlen = 3; }
else if (ch > 0xe0) { cp = ch & 0xf; runlen = 2; }
else if (ch > 0xc0) { cp = ch & 0x1f; runlen = 1; }
else return it-s.begin(); // stop on error
}
else return it-s.begin();
}
success = runlen == 0; // verify we are between codepoints
return s.length();
}