-2
    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 ?

tknkrtl
  • 87
  • 6
  • 1
    What do you mean by "and 'a' prints false,"? Also, I don't see how the first code snippet is related to your question about `@` at all. – Sweeper Jan 21 '21 at 07:54
  • 1
    _""b" and "c" prints same string"_ -- no, it doesn't. I assume you just think it does because the carriage return has no visible effect on the output. But questions like this that have false claims in them are difficult to understand, because it's never clear what the author of such a question really wants an answer to. _"when should i use "@" charachter ?"_ -- when you want to include backslash characters in the string without having to escape each one. – Peter Duniho Jan 21 '21 at 09:01

1 Answers1

3

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"

Caius Jard
  • 72,509
  • 5
  • 49
  • 80