Friday, May 6, 2011

string.Replace not behaving as expected

Can someone explain why I get different results from these two statements? I thought that reassigning the value to the same variable would result in the value I get in the above example. What am I missing here?

_body.Replace("##" + _variableName + "##",
    templateVariables[_variableName])

Hello pitty ##LastName##,

_body = _body.Replace("##" + _variableName.ToUpper() + "##", 
    templateVariables[_variableName])

Hello ##FirstName## ##LastName##,

From stackoverflow
  • Strings are immutable, so the Replace function doesn't modify the string it is called on. You need to assign it again like you did in your second example.

    And as other people have pointed out, the ToUpper call will ensure that variable names don't match.

  • You've got a call to .ToUpper() in your second example. Is this what's causing the behaviour you see?

  • If I understand this correctly: Your first statement is not assigning the return value, since replace returns a new instance of the string replaced.

    _body = _body.Replace("##" + _variableName + "##",
        templateVariables[_variableName]);
    

    should fix you there.

    The second instance you have the variable getting replace changed ToUpper() and the actual string containing mixed cased values.

    Your string should be

    Hello ##FIRSTNAME## ##LASTNAME##,
    

0 comments:

Post a Comment