简体   繁体   English

string.replace无法正常工作

[英]string.replace is not working

I have function which accepts string (which is basically a XML doc). 我有接受字符串(基本上是XML文档)的函数。 I am making this change: 我正在进行此更改:

  if (filterXml.Contains("&"))
    {
        filterXml.Replace("&", "&");
    }

It is hitting this condition but not replacing the 正在达到此条件,但没有替换

 & to &

What is wrong here? 怎么了

Remember, strings are immutable. 请记住,字符串是不可变的。 So you have to assign the return value of the Replace method (notice that it returns a String object) back to your variable. 因此,您必须将Replace方法的返回值(注意它返回一个String对象)分配回您的变量。

  if (filterXml.Contains("&"))
  {
      filterXml = filterXml.Replace("&", "&");
  }

If you're doing a lot of work with String objects, make sure to read the the String reference page 如果您要处理String对象,请确保阅读String参考页

You need to save the result: 您需要保存结果:

filterXml = filterXml.Replace("&", "&");

but I would recommend encoding ALL special XML characters. 但我建议编码所有特殊的XML字符。

You don't even need to do the Contains check. 您甚至不需要执行“包含”检查。 Just do the following: 只需执行以下操作:

filterXml = filterXml.Replace("&", "&");

If there aren't any ampersands in the string, then nothing will change. 如果字符串中没有任何“&”号,则不会有任何变化。

Try - 尝试-

  if (filterXml.Contains("&"))
    {
        filterXml = filterXml.Replace("&", "&");
    }

Strings are immutable in .net, so the replace function returns a new string rather than altering the string it is called on. 字符串在.net中是不可变的,因此replace函数将返回一个新字符串,而不是更改被调用的字符串。 You are able to assign the altered result to the variable that contained your original string value. 您可以将更改后的结果分配给包含原始字符串值的变量。

  if (filterXml.Contains("&"))
    {
        filterXml = filterXml.Replace("&", "&");
    }

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

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