如何转换为C 中的UTF8字符串

How convert to utf8 string in c++

本文关键字:中的 UTF8 字符串 何转换 转换      更新时间:2023-10-16

我有一个字符串输出,不一定是有效的UTF8。我必须将其传递给仅接受有效UTF8字符串的方法。
因此,我需要将输出转换为最接近的有效UTF8字符串,以删除无效字节或零件。我该如何在C 中这样做?我想不使用第三方库。

您应该使用icu::UnicodeString方法fromUTF8(const StringPiece &utf8)toUTF8String(StringClass &result).

如果您确定您的字符串是有效的UTF-8,只有几个损坏的字节,http://utfcpp.sourceforge.net/可以解决这个问题。从页面:

#include "utf8.h"
void fix_utf8_string(std::string& str) {
    std::string temp;
    utf8::replace_invalid(str.begin(), str.end(), back_inserter(temp));
    str = temp;
}

在处理Unicode数据时,您不使用第三方库的要求几乎是不可能的,但是UTF8-CPP库是仅标题的,这是您所能获得的。