【问题标题】:std::string character encodingstd::string 字符编码
【发布时间】:2016-03-29 18:09:58
【问题描述】:
std::string arrWords[10];
std::vector<std::string> hElemanlar;

......

this->hElemanlar.push_back(std::string(1, this->arrWords[sayKelime][j]).c_str());

......

我正在做的是:arrWord 的每个元素都是一个 std::string。我得到 arrWord 的第 n 个元素,然后将它们推入 hElemanlar。

假设 arrWords[0] 是“测试”,那么:

this->hElemanlar.push_back("t");
this->hElemanlar.push_back("e");
this->hElemanlar.push_back("s");
this->hElemanlar.push_back("t");

我的问题是虽然我对 arrWords 没有编码问题,但在 hElemanlar 中没有打印或处理好一些 utf-8 字符。 我该如何解决它?s

【问题讨论】:

  • 当您的问题陈述只是“某些 utf-8 字符未打印或处理不当”时,我们无能为力
  • 我确定“测试”没有问题。你能显示一些确实有问题的字符串吗?
  • @LightnessRacesinOrbit 问题是一些 utf-8 字符没有打印或处理得很好。
  • 重复同样的语句也不会增加价值。
  • @BoPersson 喜欢 "ğ,ş,ı,ö,ç,ü"。

标签: c++ utf-8 stdstring


【解决方案1】:

如果您知道 arrWords[i] 包含 UTF-8 编码文本,那么您可能需要将字符串拆分为完整的 Unicode 字符。

顺便说一句,而不是说:

this->hElemanlar.push_back(std::string(1, this->arrWords[sayKelime][j]).c_str());

(构造一个临时 std::string,获得它的 c 字符串表示,构造 another 临时字符串,并将其推送到向量上),例如:

this->hElemanlar.push_back(std::string(1, this->arrWords[sayKelime][j]))

无论如何。这需要变成这样:

std::string str(1, this-arrWords[sayKelime][j])
if (static_cast<unsigned char>(str[0]) >= 0xC0)
{
   for (const char c = this-arrWords[sayKelime][j+1];
        static_cast<unsigned char>(c) >= 0x80;
        j++)
   {
       str.push_back(c);
   }
}
this->hElemenlar.push_back(str);

请注意,上面的循环是安全的,因为如果j 是字符串中最后一个字符的索引,[j+1] 将返回 nul 终止符(这将结束循环)。 不过,您需要考虑递增 j 如何与您的其余代码交互。

然后,您需要考虑是否希望 hElemanlar 表示单个 Unicode 代码点(这样做),还是希望包含一个字符 + 后面的所有组合字符?在后一种情况下,您必须将上面的代码扩展为:

  • 解析下一个代码点
  • 判断是否为组合字符
  • 如果是,则在字符串上推送 UTF-8 序列。
  • 重复(一个字符上可以有多个组合字符)。

【讨论】:

  • 不幸的是它崩溃了。
猜你喜欢
  • 1970-01-01
  • 2018-03-21
  • 2019-03-13
  • 2012-06-20
  • 2018-11-24
  • 1970-01-01
  • 1970-01-01
  • 2013-09-11
  • 2014-10-13
相关资源
最近更新 更多