Replacing double backwards slashes with single ones in c#

若如初见. 提交于 2019-12-12 05:26:31

问题


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.



来源:https://stackoverflow.com/questions/13482450/replacing-double-backwards-slashes-with-single-ones-in-c-sharp

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!