我希望将控制字符范围(0x00nul到0x1F)中的任何字符音译到编码为UTF-8的Unicode符号。在C++中有简单/优雅的解决方案吗?
示例:
不要在字符串中打印'\n‘,代之以’N‘控制符号,并对所有不可打印的字符执行此操作。
␋␌␍␇␍␑␌␔␈␘␕␖ʬ␄␓␕␊
发布于 2021-02-16 06:29:50
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;
https://stackoverflow.com/questions/66226306
复制