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.
Master C and Embedded C Programming- Learn as you goEnter a string at run time and read a character to replace at console. Then, finally read a new character that has to be placed in place of an old character where ever it occurs inside the string.
String are immutable in Java. You can't change them. You need to create a new string with the character replaced.
No you can still use the object allocated on stack. For example if you have a function void f(char *p); then from main() you can pass f(a). This will pass the address of the first character to the function.
To replace all occurrences of a substring in a string by a new one, you can use the replace() or replaceAll() method: replace() : turn the substring into a regular expression and use the g flag.
Strings are immutable, so you have to make a char[]
array, change it, then make it back into a string:
string s = "foo";
char[] arr = s.ToCharArray();
arr[1] = 'x';
s = new string(arr);
Strings are immutable which is why there's no setter, you can however use a string builder:
StringBuilder s = new StringBuilder("abc");
s[1] = 'x';
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With