我有这个字符串:
std::string str = "presents";当我遍历字符时,它们的顺序如下:
spresent所以,最后一个字符在前面。
代码如下:
uint16_t c;
printf("%s: ", str.c_str());
for (unsigned int i = 0; i < str.size(); i += extractUTF8_Char(str, i, &c)) {
printf("%c", c);
}
printf("\n");下面是exctract方法:
uint8_t extractUTF8_Char(string line, int offset, uint16_t *target) {
uint8_t ch = uint8_t(line.at(offset));
if ((ch & 0xC0) == 0xC0) {
if (!target) {
return 2;
}
uint8_t ch2 = uint8_t(line.at(offset + 1));
uint16_t fullCh = (uint16_t(((ch & 0x1F) >> 2)) << 8) | ((ch & 0x3) << 0x6) | (ch2 & 0x3F);
*target = fullCh;
return 2;
}
if (target) {
*target = ch;
}
return 1;
}此方法返回字符的长度。所以:1个字节或2个字节。如果长度为2字节,则从UTF8字符串中提取Unicode点。
发布于 2010-12-18 00:21:57
您的第一个printf是打印胡言乱语(c的初始值)。未打印最后获得的c。
这是因为对extractUTF8_char的调用发生在for语句的最后一个子句中。您可能希望将其更改为
for (unsigned int i = 0; i < str.size();) {
i += extractUTF8_Char(str, i, &c);
printf("%c", c);
}而不是。
https://stackoverflow.com/questions/4472481
复制相似问题