0

Is there a C++ function to escape the control characters in a string? For example, if the input is "First\r\nSecond" the output should be "First\\0x0D\\0x0ASecond".

Hector
  • 2,464
  • 3
  • 19
  • 34
  • A greedy way of preforming this could be manually checking and replacing substrings within the main string. Refer to [C++ Replace part of a string](http://stackoverflow.com/questions/3418231/replace-part-of-a-string-with-another-string) – Brennan Mcdonald May 14 '15 at 16:38
  • There are various versions of HTTP code that performs what is known as "percent encoding", however it will encode any character that is not allowed to be in a URL. – jxh May 14 '15 at 16:57

3 Answers3

2

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();
}
W.F.
  • 13,888
  • 2
  • 34
  • 81
  • 1
    I would make the `replacementmap` variable into a static variable that is initialized with a list. – Hector May 14 '15 at 16:51
1

Is there a C++ function to escape the control characters in a string?

By that, if you mean "Is there a standard library function that you can use to accomplish that?", the answer is no.

R Sahu
  • 204,454
  • 14
  • 159
  • 270
0

I haven't heard of using raw ANSI escape codes as codes in C or C++, but i do know that some like

/n

work for creating newlines, so perhaps use

#define ActualEscapeCode AsciiEscapeCode

to substitute?

Mason Watmough
  • 495
  • 6
  • 19