How to change the nth element of a string

I have code in C # as below

string s = new string('~',25); int ind = 5; s[ind] = 'A'; 

he gives an error

The property or indexer 'string.this [int]' cannot be assigned - it is read

what is the problem and how can I fix it.

+4
source share
5 answers

Lines are immutable - you cannot modify an existing one.

Two options:

  • Use StringBuilder e.g.

     StringBuilder builder = new StringBuilder(new string('~', 25)); builder[5] = 'A'; string result = builder.ToString(); 
  • Create a new line from the char array:

     char[] chars = new string('~', 25).ToCharArray(); chars[5] = 'A'; string result = new string(chars); 

In both cases, you can fill in mutable data without creating a new line if you want - this will require more code, but will probably be more efficient.

Alternatively, you can take substrings and combine them together, according to another answer ... basically there are many ways to solve this problem. Which one is appropriate will depend on your actual use.

+10
source

Following the MSDN :

Strings are immutable - the contents of a string object cannot be changed after the object is created, although the syntax makes it look like you can do it.

Take a look at the StringBuilder class or use a char array.

+1
source

C # lines are immutable, which means that once created, you cannot change it. Instead, try using an array of characters.

0
source

Try

 s = s.Substring(0, ind) + "A" + s.Substring(ind + 1); 
0
source

You can use Stringbuilder, in which you can assign to the indexer:

 StringBuilder sb = s; int ind = 5; sb[ind] = 'A'; s = sb.ToString(); 
0
source

All Articles