Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Replace \\n with \n in a string in C#

Tags:

string

c#

I have a string

var string = "I have a a string \\nThis is a new line\\nThis is another";

what I want is

var string = "I have a a string \nThis is a new line\nThis is another";

I have used

string.Replace("\\","\");
Newline in constant

But get the error message "Newline in constant"

like image 231
Welsh King Avatar asked Jun 02 '16 12:06

Welsh King


2 Answers

Newline in constant error is caused by the fact that "\" is an invalid string literal in C#. You must have meant "\\" (to denote one literal \ symbol).

The "\\n" is a string containing 1 literal \ symbol followed with a literal n letter. You need to get "\n", a newline character. There is no \ here, it is an escape sequence. So, replacing \\ with \ can't work in principle here.

If you want to just replace all \ followed with n with a newline, you can just use .Replace(@"\n", "\n"), where @"\n" is a verbatim string literal that finds a literal \ + n, and replaces with an escape sequence \n denoting a newline (LF) symbol.

Also, you may want to use Regex.Unescape to convert all escape entities into their literal representations:

var s = "I have a a string \\nThis is a new line\\nThis is another";
Console.Write(Regex.Unescape(s));

Result of the C# demo:

I have a a string 
This is a new line
This is another
like image 129
Wiktor Stribiżew Avatar answered Sep 17 '22 15:09

Wiktor Stribiżew


What you really want to replace is a backslash followed by the letter n with the newline character

string.Replace("\\n","\n");

The reason Replace("\\","\") gives that compilation error is because the backslash is escaping the double quote so the string continues on to the end of the line which is not allowed unless it's a verbatim string (starts with an @).

like image 41
juharr Avatar answered Sep 20 '22 15:09

juharr