2
public struct Osoba{
    public string nazwisko;
    [...]
}

for (int k = 0; k < l; k++)
            {
                dlugosc = osoba[k].nazwisko.Length;
                [...]
                if (c[0] == 's' && c[1] == 'k' && c[2] == 'i')
                {
                    osoba[k].nazwisko[dlugosc - 3] = '*';
                    osoba[k].nazwisko[dlugosc - 2] = '*';
                    osoba[k].nazwisko[dlugosc - 1] = '*';
                }
            }

Hello there, I keep trying to replace 3 last letters of string, but i get this error:

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

I tried to google it, the solution was mostly adding getters and setters (i've yet to learn about it) but it didn't help me. Why can't I modify my string even thought i set everything as public?

Dargenn
  • 372
  • 4
  • 11

2 Answers2

5

Strings are immutable.You can't change a string after you created it.You need to create a new string and assign it back:

osoba[k].nazwisko = osoba[k].nazwisko.Substring(0, dlugosc - 3) + "***";
Selman Genç
  • 100,147
  • 13
  • 119
  • 184
2

Strings are immutable in .NET. It's quite unclear what you are trying to achieve but if you want to directly manipulate the contents you could use a char array instead:

public struct Osoba
{
    public char[] nazwisko;

    [...]
}
Darin Dimitrov
  • 1,023,142
  • 271
  • 3,287
  • 2,928