Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the default way to change a character at a certain index in a C# string? [duplicate]

Tags:

string

c#

I have a string like:

string s = "abc";

And I want to change the second character to a 'd' so it will be "adc" I thought this would work:

s[1] = 'd';

However I get an error:

Property or indexer 'string.this[int] 'cannot be assigned to -- it is read only

How can I accomplish this easy task (without using reasonably complicated substring methods?

like image 543
Michel Keijzers Avatar asked Dec 02 '22 16:12

Michel Keijzers


1 Answers

String is imutable. You can use StringBuilder to mutate a string:

var s = "abc";
var sb = new StringBuilder(s);
sb[1] = 'd';
s = sb.ToString();
like image 151
Eli Arbel Avatar answered Dec 14 '22 22:12

Eli Arbel