How to: Modify String Contents (C# Programming Guide)
Visual Studio 2005
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.
Example
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"; System.Console.WriteLine(str); 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); System.Console.WriteLine(str2); } }
Output
The quick brown fox jumped over the fence The quick brown cat jumped over the fence | |