Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I add \ symbol to the end of string in C#

Please forgive me a beginner's question :)

string S="abc";
S+="\";

won't complile.

string S="abc";
S+="\\";

will make S="abc\\"

How can I make S="abc\" ?

like image 570
RRM Avatar asked Feb 15 '13 13:02

RRM


5 Answers

Your second piece of code is what you want (or a verbatim string literal @"\" as others have suggested), and it only adds a single backslash - print it to the console and you'll see that.

These two pieces of code:

S += "\\";

and

S += @"\";

are exactly equivalent. In both cases, a single backslash is appended1.

I suspect you're getting confused by the debugger view, which escapes backslashes (and some other characters). You can validate that even with the debugger by looking at S.Length, which you'll see is 4 rather than 5.


1 Note that it doesn't change the data in the existing string, but it sets the value of S to refer to a new string which consists of the original with a backslash on the end. String objects in .NET are immutable - but that's a whole other topic...

like image 77
Jon Skeet Avatar answered Nov 13 '22 23:11

Jon Skeet


You can escape the backslash with the @ character:

string S="abc";
S += @"\";

But this accomplishes exactly what you've written in your second example. The confusion on this is stemming from the fact that the Visual Studio debugger continues to escape these characters, even though your source string will contain only a single backslash.

like image 45
RainbowFish Avatar answered Sep 22 '22 15:09

RainbowFish


Try this:

String S = "abc";
S += @"\";

@ = verbatim string literal

http://msdn.microsoft.com/en-us/library/aa691090%28v=vs.71%29.aspx

http://msdn.microsoft.com/en-us/library/vstudio/362314fe.aspx

like image 5
jerone Avatar answered Nov 13 '22 21:11

jerone


string S = "abs" + "\\";  

Should and does result in abc\.

What you are probably seeing is the way the debugger/intellisense visualizes the string for you. Try printing your string to the console or display it in a textbox.

like image 4
hometoast Avatar answered Nov 13 '22 21:11

hometoast


You already have the solution. The reason it appears as abc\\ whilst debugging is because VS will escape backslashes, print the value of S to a console window and you'll see abc\. You could add an @ to the start of the string literal, e.g.

string S="abc";
S+= @"\";

Which will achieve the same thing.

like image 2
DGibbs Avatar answered Nov 13 '22 21:11

DGibbs