本文介绍了c#替换\"人物的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我收到了我要通过XmlReader解析的XML字符串,并且我想去除 \"字符.

I am sent an XML string that I'm trying to parse via an XmlReader and I'm trying to strip out the \" characters.

我尝试过

.Replace(@"\", "")
.Replace("\\''", "''")
.Replace("\\''", "\"")

加上其他几种方式.

有什么想法吗?

推荐答案

您是否尝试这样:

string text = GetTextFromSomewhere();
text.Replace("\\", "");
text.Replace("\"", "");

?如果是这样,那就是问题- Replace 不会更改原始字符串,它会返回一个 new 字符串并执行替换操作...因此您想要:

? If so, that's the problem - Replace doesn't change the original string, it returns a new string with the replacement performed... so you'd want:

string text = GetTextFromSomewhere();
text = text.Replace("\\", "").Replace("\"", "");

请注意,这将替换每个反斜杠每个双引号字符;如果您只想替换 pair 反斜杠后加双引号",则可以使用:

Note that this will replace each backslash and each double-quote character; if you only wanted to replace the pair "backslash followed by double-quote" you'd just use:

string text = GetTextFromSomewhere();
text = text.Replace("\\\"", "");

(如注释中所述,这是因为字符串在.NET中是不可变的-一旦以某种方式获得了字符串对象,该字符串将始终具有相同的内容.您可以将引用分配给字符串当然是变量,但这实际上并没有改变现有字符串的内容.)

(As mentioned in the comments, this is because strings are immutable in .NET - once you've got a string object somehow, that string will always have the same contents. You can assign a reference to a different string to a variable of course, but that's not actually changing the contents of the existing string.)

这篇关于c#替换\"人物的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-31 05:59