是否有C ++函数来转义字符串中的控制字符?例如,如果输入为"First\r\nSecond"
,则输出应为"First\\0x0D\\0x0ASecond"
。
最佳答案
我还没有听说过,但是实现它应该相对容易一些:
unordered_map<char, string> replacementmap;
void initreplecementmap() {
replacementmap['\''] = "\\0x27";
replacementmap['\"'] = "\\0x22";
replacementmap['\?'] = "\\0x3f";
replacementmap['\\'] = "\\\\";
replacementmap['\a'] = "\\0x07";
replacementmap['\b'] = "\\0x08";
replacementmap['\f'] = "\\0x0c";
replacementmap['\n'] = "\\0x0a";
replacementmap['\r'] = "\\0x0d";
replacementmap['\t'] = "\\0x09";
replacementmap['\v'] = "\\0x0b";
}
string replace_escape(string s) {
stringstream ss;
for (auto c: s) {
if (replacementmap.find(c) != replacementmap.end()) {
ss << replacementmap[c];
} else {
ss << c;
}
}
return ss.str();
}
关于c++ - C++转义控制字符,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/30242577/