I think that you must write such function yourself since escape characters is a compile-time feature, i.e. when you write "\n"
the compiler would replace the \n
sequence with the eol character. The resulting string is of length 1 (excluding the terminating zero character).
In your case a string "\\n"
is of length 2 (again excluding terminating zero) and contains \
and n
.
You need to scan your string and when encountering \
check the following char. if it is one of the legal escapes, you should replace both of them with the corresponding character, otherwise skip or leave them both as is.
string unescape(const string& s)
{
string res;
string::const_iterator it = s.begin();
while (it != s.end())
{
char c = *it++;
if (c == '\\' && it != s.end())
{
switch (*it++) {
case '\\': c="\\"; break;
case 'n': c="\n"; break;
case 't': c="\t"; break;
// all other escapes
default:
// invalid escape sequence - skip it. alternatively you can copy it as is, throw an exception...
continue;
}
}
res += c;
}
return res;
}