【问题标题】:how to replace all occurrences (in a std::string) of a specific ascii char with a unicode char如何用 unicode char 替换特定 ascii char 的所有出现(在 std::string 中)
【发布时间】:2021-04-10 08:19:42
【问题描述】:

如何将 std::string 中出现的每个特定 ascii 字符替换为 unicode 字符?

我正在尝试(以 em dash 为例)

string mystring;
replace(mystring.begin(), mystring.end(), ' ', '—'); // error: 2nd char is too wide for char
replace(mystring.begin(), mystring.end(), " ", "—"); // error: replace() does not exist

我当然可以编写一个循环,但我希望有一个可用的标准函数。我知道修改后的字符串会比原始字符串长。

似乎是一个愚蠢的基本问题,但 1 小时的谷歌搜索解决了 zilch。

【问题讨论】:

  • C++ 本身不提供任何处理 Unicode 字符串的工具。它逐字节处理字符串,这仅适用于 ascii。你需要一些 Unicode 库。
  • std::string 真的不支持 unicode。底层类型是charstring 期望每个元素都是它自己独特的字形,不像 unicode 可以将多个元素组合成一个字形
  • "带有 unicode 字符" - 带有多长的 Unicode 字符?你应该知道C++ 有unicode string literlas,你很可能熟悉en.cppreference.com/w/cpp/localecodecvt。那你有什么问题?
  • @BoBTFish 谢谢。我会调查 boost 是否有。

标签: c++ string replace unicode


【解决方案1】:

std::string 只知道任意的char 元素,但不知道chars 实际代表什么。您有责任决定将std::string 的内容编码为什么字符集,然后将Unicode 字符编码为同一字符集。例如,在 UTF-8 中, (U+2014 EM DASH) 是 3 chars: 0xE2 0x80 0x94,但在 Windows-125x 字符集中它只有 1 char: 0x97

您可以使用std::string::find()方法找到1-charASCII字符的索引,然后使用std::string::replace()方法替换char编码的Unicode字符,例如:

string mystring = ...;
string replacement = ...; // "\xE2\x80\x94", "\x97", etc...
string::size_type pos = 0;
while ((pos = mystring.find(' ', pos)) != string::npos) {
    mystring.replace(pos, 1, replacement);
    pos += replacement.size();
}

【讨论】:

    【解决方案2】:

    提升,哦,是的,有诀窍

    #include <boost/algorithm/string/replace.hpp>
    ...
    boost::replace_all(mystring, " ", "—");
    

    https://www.boost.org/doc/libs/1_47_0/doc/html/boost/algorithm/ireplace_all.html

    仅使用标准库(虽然很冗长):

    string tmp;
    std::regex_replace(back_inserter(tmp), mystring.begin(), mystring.end(), std::regex(" "), "—");
    mystring = tmp;
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-08-02
      • 2016-07-09
      • 2014-01-09
      • 2012-01-07
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多