I want to do this:
string s = "abc";
s[1] = 'x';
and s will become "axc". However, it seems that string[i] only has a getter and has no setter. The compiler gives me the following error:
"Property or indexer 'string.this[int]' cannot be assigned to -- it is read only"
I guess I could make a loop and change the char i want. but i was just wondering if there is an easy way to do it? And why there isn't a setter for string[i]?
Thanks in advance.
Remember, in managed and safe .Net, strings are immutable, so even if you could do the above, you'd really be creating a new copy of the string with the replacement.
If you are only replacing one character, a simple loop is probably your best bet.
However, if you are going to make multiple replacements, consider using a
StringBuilder
:Strings are immutable, so you have to make a
char[]
array, change it, then make it back into a string: