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 ?
You declared string
a
to end with carriagereturn character:So you must replace the carriage return with nothing:
If you had declared the string to end with "backslash r":
Then you would have succeeded in replacing "backslash r" with nothing:
This would also work:
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 itUltimately 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"