Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

string class Replace and Stringbuilder replace

Tags:

c#

string s = "value_test_this";
string m = s.Replace('e','E');

StringBuilder strBuilder  = new StringBuilder("value_test_this");
strBuilder.Replace('e','E');

since strings are immutable, how does the Replace works in string class,

like image 568
Raghav55 Avatar asked Mar 20 '26 13:03

Raghav55


2 Answers

It creates another string in the memory and then points the m to that new string. The old string also stays in the memory.

And that is exactly why StringBuilder should be used if frequent modifications have to be made to the string.

If you want to know why Strings are immutable in C#, look at this SO discussion

like image 135
Aamir Avatar answered Mar 23 '26 03:03

Aamir


If you do a string.Replace it's simply going to create a new string (since, as you said, it is immutable). In StringBuilder there's no new string being created, the one you have gets modified.

like image 32
alex Avatar answered Mar 23 '26 01:03

alex



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!