字符串是不可变的,因此不能修改字符串的内容。但是,可以将字符串的内容提取到非不可变的窗体中,并对其进行修改,以形成新的字符串实例。

示例

下面的示例使用 ToCharArray 方法来将字符串的内容提取到 char 类型的数组中。然后修改此数组中的某些元素。之后,使用 char 数组创建新的字符串实例。

C# CopyCode image复制代码
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);
    }
}

输出

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

请参见