I think that you must write such function yourself since escape characters is a compile-time feature, i.e. when you write "
"
the compiler would replace the
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.
( http://ideone.com/BvcDE ):
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 = '
'; break;
case 't': c = ''; 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;
}
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…