Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there an easy way to change a char in a string in C#?

Tags:

string

c#

char

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.

like image 850
StarCub Avatar asked Jul 16 '10 10:07

StarCub


People also ask

Can I replace a character in a string in C?

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.

Can you change a char in a string?

String are immutable in Java. You can't change them. You need to create a new string with the character replaced.

Can we modify char * in C?

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.

How do you replace all characters in a string?

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.


2 Answers

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);
like image 90
Callum Rogers Avatar answered Sep 28 '22 03:09

Callum Rogers


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';
like image 23
John Warlow Avatar answered Sep 28 '22 03:09

John Warlow