【发布时间】:2021-02-16 14:29:50
【问题描述】:
我想将控制字符范围(0x00 NUL 到 0x1F)中的任何字符音译为编码为 UTF-8 的字符的 Unicode 符号。你有一个简单/优雅的 C++ 解决方案吗?
例子:
不要在字符串中打印“\n”,而是将其替换为“N-L”控制符号,并对所有不可打印的字符执行此操作。
␋␌␍␇␍␑␌␔␈␘␕␖ʬ␄␓␕␊
【问题讨论】:
标签: c++
我想将控制字符范围(0x00 NUL 到 0x1F)中的任何字符音译为编码为 UTF-8 的字符的 Unicode 符号。你有一个简单/优雅的 C++ 解决方案吗?
例子:
不要在字符串中打印“\n”,而是将其替换为“N-L”控制符号,并对所有不可打印的字符执行此操作。
␋␌␍␇␍␑␌␔␈␘␕␖ʬ␄␓␕␊
【问题讨论】:
标签: c++
std::string ReplaceASCIIControlCharacters(std::string input)
{
std::vector<uint8_t> output;
output.reserve(input.length());
for (char c : input) {
if (c >= 0x00 && c <= 0x1F) {
output.push_back(0xe2);
output.push_back(0x90);
output.push_back(0x80 + c);
} else {
output.push_back(c);
}
}
return std::string(output.begin(), output.end());
}
std::string output;
output.reserve(input.length());
for (char c : input) {
if (c >= 0x00 && c <= 0x1F) {
output.append({0xe2, 0x90, 0x80 + c});
} else {
output.push_back(c);
}
}
return output;
【讨论】:
output.assign(output.end(), {0xex, 0x90, 0x80+c}); - 可能会更有效。
string::assign() 重载。我想你的意思是string::insert()。甚至只是string::append()。
vector 而不是直接构建返回的字符串?
vector:std::string output; output.reserve(input.length()); for (char c : input) { if (c >= 0x00 && c <= 0x1F) { output.append({0xe2, 0x90, 0x80 + c}); } else { output.push_back(c); } } return output;