C++:字符串的字符迭代(我疯了)

Mar*_*aux 1 c++ string iterator

我有这个字符串:

std::string str = "presents";
Run Code Online (Sandbox Code Playgroud)

当我遍历字符时,它们按此顺序排列:

spresent
Run Code Online (Sandbox Code Playgroud)

所以,最后一个char首先出现.

这是代码:

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");
Run Code Online (Sandbox Code Playgroud)

这是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;
}
Run Code Online (Sandbox Code Playgroud)

此方法返回字符的长度.所以:1个字节或2个字节.如果长度为2个字节,则从UTF8字符串中提取UNICODE点.

lij*_*jie 17

你的第一个printf是打印废话(初始值c).最后c得到的不打印.

这是因为调用extractUTF8_char发生在for语句的最后一个子句中.您可能想要将其更改为

for (unsigned int i = 0; i < str.size();) {
    i += extractUTF8_Char(str, i, &c);
    printf("%c", c);
}
Run Code Online (Sandbox Code Playgroud)

代替.