TWood
TWood

Reputation: 2583

formatting strings with backslash

I'm a newbie to c# so hopefully this one isn't too hard for a few of you.

I'm trying to build a string that has a \ in it and I am having difficulty getting just one backslash to show up even though I am adding additional escape chars or ignoring them all together. Can someone show me what I am doing wrong?

What I want my string to look like:

"10.20.14.103\sql08"

What I've tried so far:

I added an additional character to make the compiler happy but it did not escape it.

ip = string.Format("{0}\\\\{1}", ip, instancename); // output has 2 \'s

I told it to ignore escapes, it decided to ignore me instead

string temp =  @"192.168.1.200\sql08"; // output has 2 \'s

Can someone help me make sense of this? (The richtext editor here seems to do a better job with it than VS2010 is doing, lol)

Upvotes: 2

Views: 11114

Answers (4)

Pritesh
Pritesh

Reputation: 3288

string requiredString = string.Format(@"{0}\\{1}",str1,str2);

Upvotes: 1

Dan Tao
Dan Tao

Reputation: 128427

I'm guessing you're getting confused by the debugger.

If you hover your mouse over a local variable in VS, strings will be escaped so a single \ will display as \\.

To see what your string really is, output it somewhere for display (e.g., to the console) or hover your mouse on the variable, click on the arrow next to the little magnifying glass that appears, and select "Text Visualizer."

Upvotes: 13

Justin Niessner
Justin Niessner

Reputation: 245489

I'm guessing you're looking at the values in the debugger and seeing that they have two slashes.

That's normal. The debugger will show two slashes even though the actual string representation will only have one. Just another hump to get over when getting used to the debugger.

Be assured that when you actually use your strings, they will still only have a single slash (using either of your methods).

Upvotes: 3

Adam Robinson
Adam Robinson

Reputation: 185703

If you're looking at these strings in the debugger (i.e., by hovering the mouse over the variable or using a watch), the debugger adds escape characters to the display string so that it's a valid string expression. If you want to view the string verbatim in this fashion, click on the magnifying glass on the right side of the tooltip or watch entry with the string in it.

Upvotes: 4

Related Questions