简体   繁体   中英

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

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.)

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

一种方法是使用逐字字符串文字

string.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