简体   繁体   中英

String.replace “\\” with “/”

There seem to be a lot of questions around this but none of the ones I found seemed to work for me.

My code:

string subFolderName = category = "Parent/Sub\\Sub sub";
string category = subFolderName.Replace(@"\\", @"/");

This returns category as the same string as subFoldername , ie:

"Parent/Sub\\Sub sub".

What I actually want is:

"Parent/Sub/Sub sub"

Just try

string category = subFolderName.Replace(@"\", @"/");

It will work, because category = "Parent/Sub\\\\Sub sub"; contains a single \\

As Damien_The_Unbeliever said in his comment , when you write "Parent/Sub\\\\Sub sub" as a string, actually it contains only one \\ character. So, String.Replace method can't find \\\\ in your string.

When you use verbatim string literal , your string will be exactly how you wrote it.

string subFolderName = category = @"Parent/Sub\\Sub sub";
string category = subFolderName.Replace(@"\\", @"/");
Console.WriteLine(category);

Outpuw will be;

Parent/Sub/Sub sub

Here is a DEMO .

How are you looking at the contents of category? If you are using the VS debugger then it will escape the string so \\ in the string will appear as \\\\

so you either need

string category = subFolderName.Replace(@"\", @"/");

or

string category = subFolderName.Replace("\\", "/");
string category = subFolderName.Replace(@"\", "/");

用这个。

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM