Verbatim string replace

241 Views Asked by At
    var a = "asdfgh\r";
    Console.WriteLine(a.Contains(@"\r"));
    var b = a.Replace(@"\r","").Replace(@"\n","");
    var c = a.Replace("\r","").Replace("\n","");
    Console.WriteLine(a);
    Console.WriteLine(b);
    Console.WriteLine(c);

"b" and "c" prints same string and "a" prints false,

I was trying to replace \r and \n to an empty char so first i tried below code, there's a backslash in "\r" and "\n" so i decided to use "@" before them ;

var b = a.Replace(@"\r","").Replace(@"\n","")

but this didn't work,

var c = a.Replace("\r","").Replace("\n","");

this works, so im confused when should i use "@" charachter ?

1

There are 1 best solutions below

0
On BEST ANSWER

You declared string a to end with carriagereturn character:

var a = "asdfgh\r"; //it has a length of 7 when compiled 

So you must replace the carriage return with nothing:

Replace("\r","")

If you had declared the string to end with "backslash r":

var a = @"asdfgh\r"; //it has a length of 8 when compiled 

Then you would have succeeded in replacing "backslash r" with nothing:

Replace(@"\r","")

This would also work:

Replace("\\r","")

Because the double slash is turned into a single and then the r is a normal character so you're replacing "backslash r" and not carriagereturn


When compiling the C# compiler looks for \ in a string and converts the following character(s) according to some rule. Using @ before the string turns this off. Mostly it's useful for paths. Remember that it's a compile time thing, not something you need to do to variables that hold data entered in runtime. Putting an @ before a variable name means something different - allowing you to call a variable a reserved word, like string @for = "for" - deplorable practice; don't do it

Ultimately the problem is that you were inconsistent when declaring your strings - a was not a verbatim string so it really did have a single carriage return char, and then you were trying to replace using a verbatim string (and "backslash r" is a different string to "carriagereturn"