Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
85 views
in Technique[技术] by (71.8m points)

c# - string.Replace (or other string modification) not working

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.

Question&Answers:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

2.1m questions

2.1m answers

60 comments

57.0k users

...