string.Replace (or other string modification) not

2019-01-01 04:27发布

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

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

when I debug and check parameters they have values I expect - i.e. someID.ToString() got "1087163075", and sessionID has "108716308" and someTestString contains "1087163075".

I have no idea why this would not work change someTestString

Complete sample:

string someTestString = 
      "<a href='myfoldert/108716305-1.jpg' target='_blank'>108716305-1.jpg</a>"
someTestString.Replace("108716305", "NewId42");  

the result (in someTestString) should be this:

"<a href='myfoldert/NewId42-1.jpg' target='_blank'>NewId42-1.jpg</a>" 

but it doesn't change. The string for someTestString remains unchanged after hitting my code.

标签: c#
4条回答
孤独总比滥情好
2楼-- · 2019-01-01 04:35
someTestString = someTestString.Replace(someID.ToString(), sessionID);

that should work for you

查看更多
琉璃瓶的回忆
3楼-- · 2019-01-01 04:45

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

string newstring = someTestString.Replace(someID.ToString(), sessionID);
查看更多
爱死公子算了
4楼-- · 2019-01-01 04:47

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.

查看更多
何处买醉
5楼-- · 2019-01-01 04:53

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, trim and substring variants - all of them return new string as original string can't be modified.

查看更多
登录 后发表回答