string replace on escape characters

LoveMeSomeCode picture LoveMeSomeCode · Dec 10, 2008 · Viewed 17.2k times · Source

Today I found out that putting strings in a resource file will cause them to be treated as literals, i.e putting "Text for first line \n Text for second line" will cause the escape character itself to become escaped, and so what's stored is "Text for first line \n Text for second line" - and then these come out in the display, instead of my carriage returns and tabs

So what I'd like to do is use string.replace to turn \\ into \ - this doesn't seem to work.

s.Replace("\\\\", "\\"); 

doesn't change the string at all because the string thinks there's only 1 backslash

s.Replace("\\", "");

replaces all the double quotes and leaves me with just n instead of \n

also, using @ and half as many \ chars or the Regex.Replace method give the same result

anyone know of a good way to do this without looping through character by character?

Answer

codelogic picture codelogic · Dec 10, 2008

Since \n is actually a single character, you cannot acheive this by simply replacing the backslashes in the string. You will need to replace each pair of \ and the following character with the escaped character, like:

s.Replace("\\n", "\n");
s.Replace("\\t", "\t");
etc