RG-3
RG-3

Reputation: 6188

string.replace is not working

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?

Upvotes: 1

Views: 648

Answers (5)

Babak Naffas
Babak Naffas

Reputation: 12571

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

Upvotes: 13

ipr101
ipr101

Reputation: 24236

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.

Upvotes: 4

DJ Quimby
DJ Quimby

Reputation: 3699

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.

Upvotes: 6

AndrewC
AndrewC

Reputation: 6730

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

Upvotes: 1

Jared Peless
Jared Peless

Reputation: 1120

You need to save the result:

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

but I would recommend encoding ALL special XML characters.

Upvotes: 7

Related Questions