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.
Strings are immutable which is why there's no setter, you can however use a string builder:
I don't think you can do this in C#, as the string cannot be altered (just destroyed and recreated). Have a look at the StringBuilder class.
(Your example is slightly wrong: s[2] = 'x' should change it to "abx".)
No you can't, since strings are immutable, you have to create a new string:
You should use a method that returns a new string with the desired modification.
Hope that helps!
Why not do this if you're using some Linq
That should let you replace whatever char you want with whatever char you want.
What's about this?
yes in c# string can not be altered.
but we can try this
answer will be "axc". as this will replace the old string with new string.