string.Replace (or other string modification) not working

前端 未结 4 489
误落风尘
误落风尘 2020-11-22 06:17

For the following code, I can\'t get the string.Replace to work:

someTestString.Replace(someID.ToString(), sessionID);

when I

相关标签:
4条回答
  • 2020-11-22 06:45
    someTestString = someTestString.Replace(someID.ToString(), sessionID);
    

    that should work for you

    0 讨论(0)
  • 2020-11-22 06:51

    You can achieve the desired effect by using

    someTestString = someTestString.Replace(someID.ToString(), sessionID);
    

    As womp said, strings are immutable, which means their values cannot be changed without changing the entire object.

    0 讨论(0)
  • 2020-11-22 06:58

    Strings are immutable. The result of string.Replace is a new string with the replaced value.

    You can either store result in new variable:

    var newString = someTestString.Replace(someID.ToString(), sessionID);
    

    or just reassign to original variable if you just want observe "string updated" behavior:

    someTestString = someTestString.Replace(someID.ToString(), sessionID);
    

    Note that this applies to all other string functions like Remove, Insert, trim and substring variants - all of them return new string as original string can't be modified.

    0 讨论(0)
  • 2020-11-22 07:08

    strings are immutable, the replace will return a new string so you need something like

    string newstring = someTestString.Replace(someID.ToString(), sessionID);
    
    0 讨论(0)
提交回复
热议问题