Jade M
Jade M

Reputation: 3101

How can I replace "/" with "\/" in a string?

I would like to do the following:

if (string.Contains("/"))
{
  string.Replace("/", "\/"); //this isn't valid
}

I've tried

string.Replace("/", "\\/"); 

but this gives me what I started with. How can I do this?

Thanks

Upvotes: 1

Views: 1115

Answers (3)

Bryan
Bryan

Reputation: 8788

One way is to use a verbatim string literal

string.Replace("/", @"\");

Upvotes: 1

Christian C. Salvadó
Christian C. Salvadó

Reputation: 828002

Strings are immutable, which means that any modification you do to a string results in a new one, you should assign the result of the Replace method:

if (myString.Contains("/"))
{
  myString  = myString.Replace("/", "\\/"); 
}

Upvotes: 3

Jon Skeet
Jon Skeet

Reputation: 1503489

String.Replace returns the string with replacements made - it doesn't change the string itself. It can't; strings are immutable. You need something like:

text = text.Replace("/", "\\/");

(In future examples, it would be helpful if you could use valid variable names btw. It means that those wishing to respond with working code can use the same names as you've used.)

Upvotes: 3

Related Questions