Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Access a string as an array, check the value of an index and perhaps change the character in that index

Tags:

string

c#

.net

I have been trying to read a string and then one by one for each character run a random number if a 5 is generated then change the character from a 1 to a 0 or vice versa. I feel I am almost there this is my thirds attempt at this, but I have a slight problem with writing to the index, as it tells me it is read only. Here is my code:

string mutate = "1010";

for (int i = 0; i < 4; i++)
{
    int MutProbablity = random.Next(1, 1000);
    if (MutProbablity == 5)
    {
        if (mutate[i] == '0')
        {
            mutate[i] = '1';
        }
        else if (mutate[i] == '1')
        {
            mutate[i] = '0';
        }
    }
}

This is my error:

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

Can someone tell me how I can get around this issue or perhaps suggest a different way I can achieve my goal?

like image 828
deucalion0 Avatar asked Dec 04 '25 00:12

deucalion0


1 Answers

Strings in .NET are immutable, so you won't be able to modify any characters, but you can accomplish your goal by first converting it to a char[], which is mutable.

Like this:

var chars = mutate.ToCharArray();     // convert to char[]
for (int i = 0; i < 4; i++)
{
    int MutProbablity = random.Next(1, 1000);
    if (MutProbablity == 5)
    {
        if (chars[i] == '0')
        {
            chars[i] = '1';
        }
        else if (chars[i] == '1')
        {
            chars[i] = '0';
        }
    }
}

mutate = new String(chars);    // convert to back to string

Another way to do this would be to use Linq (and an admittedly very ugly string of ternary operators).

var new string(mutate.Select(c => 
    (random.Next(1, 1000) == 5) ? ((c == '0') ? '1' : (c == '1') ? '0' : c) : c).ToArray());
like image 146
p.s.w.g Avatar answered Dec 06 '25 14:12

p.s.w.g



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!