开发者

string.replace is not working

开发者 https://www.devze.com 2023-04-10 02:03 出处:网络
I have function which accepts string (which is basically a XML doc). I am making this change: if (filterXml.Contains(\"&\"))

I have function which accepts string (which is basically a XML doc). 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.

  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


You need to save the result:

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

but I would recommend encoding ALL special XML characters.


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. You are able to assign the altered result to the variable that contained your original string value.


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

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号