Robert
Robert

Reputation: 5302

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"

Upvotes: 2

Views: 887

Answers (4)

Soner Gönül
Soner Gönül

Reputation: 98868

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.

Upvotes: 2

Vineet Singla
Vineet Singla

Reputation: 1677

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

Use this.

Upvotes: 1

Bob Vale
Bob Vale

Reputation: 18474

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("\\", "/");

Upvotes: 1

I4V
I4V

Reputation: 35363

Just try

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

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

Upvotes: 6

Related Questions