简体   繁体   English

如何在字符串中用“ \\ /”替换“ /”?

[英]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. String.Replace 返回已替换的字符串-不会更改字符串本身。 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.) (在以后的示例中,如果可以使用有效的变量名btw会很有帮助。这意味着希望使用工作代码进行响应的人可以使用与您使用的相同的名称。)

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: 字符串是不可变的,这意味着您对字符串所做的任何修改都会导致新的修改,您应该分配Replace方法的结果:

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

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

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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