简体   繁体   English

C ++转义控制字符

[英]C++ escape control characters

Is there a C++ function to escape the control characters in a string? 是否有C ++函数可以对字符串中的控制字符进行转义? For example, if the input is "First\\r\\nSecond" the output should be "First\\\\0x0D\\\\0x0ASecond" . 例如,如果输入为"First\\r\\nSecond"则输出应为"First\\\\0x0D\\\\0x0ASecond"

I haven't heard about any but it should be relatively easy to implement one: 我还没有听说过,但是实现它应该相对容易一些:

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();
}

Is there a C++ function to escape the control characters in a string? 是否有C ++函数可以对字符串中的控制字符进行转义?

By that, if you mean "Is there a standard library function that you can use to accomplish that?", the answer is no. 那样的话,如果您的意思是“是否存在可用于完成此任务的标准库函数?”,答案是否定的。

I haven't heard of using raw ANSI escape codes as codes in C or C++, but i do know that some like 我还没有听说过将原始ANSI转义代码用作C或C ++中的代码,但我确实知道有些类似

/n

work for creating newlines, so perhaps use 为创建换行而工作,所以也许使用

#define ActualEscapeCode AsciiEscapeCode

to substitute? 来代替?

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM