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\" ?
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...
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.
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
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With