std::string 上的 substr 无法正常工作,因为存在一些不可见但看起来像空格的字符

substr on std::string doesn't work correctly due to presence of some characters that are invisible, but look like spaces

本文关键字:存在 看起来 字符 空格 因为 substr 上的 string 常工作 工作 std      更新时间:2023-10-16

我有一个 std::string,其中包含我看不到的字符,例如 xc2等。

我想要字符串的子字符串,因为字符的存在诸如"时,我的字符串无法正常工作。尽管解决了这个问题,但我不希望其他任何角色弄乱这个问题。如何解决这个问题?[我只想用空格替换所有这些不必要的字符。]

您的文本很可能是UTF-8 Unicode(这是当今最常见的编码)。 XC2是可能"无爆破空间"(C2 A0)字符或类似内容的多字节编码的一部分。STD :: String和子字符串在字节上运行,并且完全不知道您具有Unicode,并且某些对字节不应拆分。您还将获得不正确的角色计数,不正确的资本化和其他奇怪的效果。

处理此问题的正确方法是使用正确实现Unicode的库。这意味着用Unicode Aware Araine替换程序中的所有字符串。

我知道这有点工作,但是另一种选择是,您今天和明天在其他地方找到了另一个操作,可以做错事。

您可以使用std::wstring_convert<std::codecvt_utf8_utf16<char16_t>,char16_t>

将此字符串转换为std::u16string

示例:

    #include <codecvt>
    //Something...
    std::string hello = "H€llo World"; 
    std::wstring_convert<std::codecvt_utf8_utf16<char16_t>,char16_t> convert;
    std::u16string hello_word_u16 = convert.from_bytes(hello); 
    std::string hello_world_u8 = convert.to_bytes(hello_word_u16);

使用U16(char16_t),您不需要关心双字节编码字符。