Replacing double backwards slashes with single one

2019-08-19 10:56发布

问题:

I need to replace double quotes with single so that something like this

\\\\servername\\dir1\\subdir1\\

becomes

\\servername\dir1\subdir1\

I tried this

string dir = "\\\\servername\\dir1\\subdir1\\";
string s = dir.Replace(@"\\", @"\"); 

The result I get is

\\servername\\dir1\\subdir1\\

Any ideas?

回答1:

You don't need to replace anything here. The backslashes are escaped, that's why they are doubled.
Just like \t represents a tabulator, \\ represents a single \. You can see the full list of Escape Sequences on MSDN.

string dir = "\\\\servername\\dir1\\subdir1\\";
Console.WriteLine(dir);

This will output \\servername\dir1\subdir1\.

BTW: You can use the verbatim string to make it more readable:

string dir = @"\\servername\dir1\subdir1\";


回答2:

There is no problem with the code for replacing. The result that you get is:

\servername\dir1\subdir1\

When you are looking at the result in the debugger, it's shown as it would be written as a literal string, so a backslash characters is shown as two backslash characters.

The string that you create isn't what you think it is. This code:

string dir = "\\\\servername\\dir1\\subdir1\\";

produces a string containing:

\\servername\dir1\subdir1\

The replacement code does replace the \\ at the beginning of the string.

If you want to produce the string \\\\servername\\dir1\\subdir1\\, you use:

string dir = @"\\\\servername\\dir1\\subdir1\\";

or:

string dir = "\\\\\\\\servername\\\\dir1\\\\subdir1\\\\";


回答3:

This string "\\\\servername\\dir1\\subdir1\\" is the same as @"\\servername\dir1\subdir1\". In order to escape backslashes you need either use @ symbol before string, or use double backslash instead of one.

Why you need that? Because in C# backslash used for escape sequences.