This documentation is archived and is not being maintained.

How to: Modify String Contents (C# Programming Guide)

Strings are immutable, so it is not possible to modify the contents of string. The contents of a string can, however, be extracted into a non-immutable form, modified, and then formed into a new string instance.


The following example uses the ToCharArray method to extract the contents of a string into an array of the char type. Some of the elements of this array are then modified. The char array is then used to create a new string instance.

class ModifyStrings
    static void Main()
        string str = "The quick brown fox jumped over the fence";

        char[] chars = str.ToCharArray();
        int animalIndex = str.IndexOf("fox");
        if (animalIndex != -1)
            chars[animalIndex++] = 'c';
            chars[animalIndex++] = 'a';
            chars[animalIndex] = 't';

        string str2 = new string(chars);


The quick brown fox jumped over the fence
The quick brown cat jumped over the fence

See Also