C#字符串替换,无法正常工作
我有一个字符串,我从中读到:
TextReader tr = new StreamReader(this.dataPath ); string contents = tr.ReadToEnd();
内容的价值以:
"\r\n....."
当我尝试执行
string styleSheet = ""; string xmlString = ""; TextReader tr = new StreamReader(this.dataPath ); string contents = tr.ReadToEnd(); contents.Replace(xmlString,xmlString + styleSheet );
它绝对不会找到第一次出现的XmlString。 有什么想法吗?
尝试
contents = contents.Replace(xmlString,xmlString + styleSheet );
这是因为String类是不可变的。
Replace()方法返回一个新的字符串对象,因此您必须将代码更改为:
content = contents.Replace(xmlString,xmlString + styleSheet );
你可能想这样做:
string styleSheet = ""; string xmlString = ""; TextReader tr = new StreamReader(this.dataPath ); string contents = tr.ReadToEnd(); string result = contents.Replace(xmlString,xmlString + styleSheet );
您目前没有捕获您在最后一行上执行的替换结果。
System.String
是不可变的。 诸如Replace
操作返回一个新字符串而不是修改this
字符串。 如果您确实需要可变字符串或只是将Replace
调用的结果赋给变量,请使用System.Text.StringBuilder
。
如果您正在搜索字符串,那么要获得技术(以及谁不喜欢它)
\r\n.....
搜索字符串必须是
"\\r\\n"
要么
@"\r\n"
这并没有真正回答你的问题,但已经多次回答,所以请允许我放在一边。
我见过许多人将流内容读入字符串的情况,这样就可以完成一些非常简单的操作。 在许多情况下,当然在这种情况下,可以执行操作,而无需复制整个字符串并进行处理。
通过比现有代码更多的努力,您可以编写一个StreamStringReplace方法,该方法将输入流,输出流,查找字符串和替换字符串作为其参数。 这会更有效,特别是如果你的xml文档可以变大。