C++ 删除非 utf8

c++ remove non utf8

我正在努力验证字符串是否为 utf8。 我从 glib 中找到了方法 g_utf8_validate,其中 returns:

有没有可能超越这个,并且在非utf8部分之后也得到有效数据?示例:

std::string invalid = "okdata\xa0\xa1morevalid";

Currenlty 我可以存 "okdata" 但我想存 "okdatamorevalid".

有什么想法吗?谢谢。

您可以继续对剩余字符串调用 g_utf8_validate(每次都跳过第一个字节)以找到更多有效部分:

#include <iostream>
#include <string>

#include <glib.h>

int main() {
  char const *data = "okdata\xa0\xa1morevalid";
  std::string s;

  // Under the assumption that the string is null-terminated.
  // Otherwise you'll have to know the length in advance, pass it to
  // g_utf8_validate and reduce it by (pend - p) every iteration. The
  // loop condition would then be remaining_size > 0 instead of *pend != '[=10=]'.
  for(char const *p = data, *pend = data; *pend != '[=10=]'; p = pend + 1) {
    g_utf8_validate(p, -1, &pend);
    s.append(p, pend);
  }

  std::cout << s << std::endl; // prints "okdatamorevalid"
}

可以循环调用。像这样:

std::string sanitize_utf8(const std::string &in) {
    std::string result;
    const char *ptr = in.data(), *end = ptr + in.size();
    while (true) {
        const char *ptr2;
        g_utf8_validate(ptr, end - ptr, &ptr2);
        result.append(ptr, ptr2);
        if (ptr2 == end)
            break;
        ptr = ptr2 + 1;
    }
    return result;
}