What is the default way to change a character with a specific index in a C # line?

I have a line like:

string s = "abc";

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

s[1] = 'd';

However, I get the error message:

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

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

+4
source share
5 answers

Stringcan be deduced. You can use StringBuilderto change the line:

var s = "abc";
var sb = new StringBuilder(s);
sb[1] = 'd';
s = sb.ToString();
+13
source

The error message is clear, the String.Charsproperty is read-only. You cannot understand this.

Here is how it is defined:

public char this[
    int index
] { get; }

As you can see, there is no accessor set.

String.Remove String.Insert . LINQPad;

string s = "abc";
s = s.Remove(1, 1).Insert(1, "d");
s.Dump(); //adc

, string . . . , , .

StringBuilder , StringBuilder.Chars .

var sb = new StringBuilder("abc");
sb[1] = 'd';
sb.Dump();  // adc
+2

, unsafe:

fixed (char* pfixed = s)
    pfixed[1] = 'd';
+2

. , . ​​, StringBuilder.

+1

Enumerable.Select:

string s = "abc";
string n = new string(s.Select((c, index) => 
            {
                if (index == 1)
                    return 'd';
                else
                    return c;
            }).ToArray());
Console.WriteLine(n);  // adc
+1
source

Source: https://habr.com/ru/post/1533055/


All Articles