Share via


HOW TO:修改字串內容 (C# 程式設計手冊)

因為字串是「不可變的」(Immutable),無法 (在沒有使用 unsafe 程式碼的情況下) 在建立字串物件之後修改其值, 但有許多方式可以修改字串值,並將結果儲存至新字串物件。 System.String 類別 (Class) 提供可根據輸入字串來操作並傳回新字串物件的方法。 在許多情況下,您都可以將新物件指派給存放原始字串的變數。 System.Text.RegularExpressions.Regex 類別可提供運作方式都類似的其他方法。 System.Text.StringBuilder 類別提供可讓您「就地」修改的字元緩衝區。您可以呼叫 StringBuilder.ToString 方法,建立含有目前緩衝區內容的新字串物件。

範例

在下列範例中,會示範不同的方式,取代或移除指定之字串的子字串。

class ReplaceSubstrings
{
    string searchFor;
    string replaceWith;

    static void Main(string[] args)
    {

        ReplaceSubstrings app = new ReplaceSubstrings();
        string s = "The mountains are behind the clouds today.";

        // Replace one substring with another with String.Replace.
        // Only exact matches are supported.
        s = s.Replace("mountains", "peaks");
        Console.WriteLine(s);
        // Output: The peaks are behind the clouds today.

        // Use Regex.Replace for more flexibility. 
        // Replace "the" or "The" with "many" or "Many".
        // using System.Text.RegularExpressions
        app.searchFor = "the"; // A very simple regular expression.
        app.replaceWith = "many";
        s = Regex.Replace(s, app.searchFor, app.ReplaceMatchCase, RegexOptions.IgnoreCase);
        Console.WriteLine(s);
        // Output: Many peaks are behind many clouds today.

        // Replace all occurrences of one char with another.
        s = s.Replace(' ', '_');
        Console.WriteLine(s);
        // Output: Many_peaks_are_behind_many_clouds_today.

        // Remove a substring from the middle of the string.
        string temp = "many_";
        int i = s.IndexOf(temp);
        if (i >= 0)
        {
            s = s.Remove(i, temp.Length);
        }
        Console.WriteLine(s);
        // Output: Many_peaks_are_behind_clouds_today.

        // Remove trailing and leading whitespace.
        // See also the TrimStart and TrimEnd methods.
        string s2 = "    I'm wider than I need to be.      ";
        // Store the results in a new string variable.
        temp = s2.Trim();
        Console.WriteLine(temp);
        // Output: I'm wider than I need to be.

        // Keep the console window open in debug mode.
        Console.WriteLine("Press any key to exit");
        Console.ReadKey();
    }

    // Custom match method called by Regex.Replace
    // using System.Text.RegularExpressions
    string ReplaceMatchCase(Match m)
    {
        // Test whether the match is capitalized
        if (Char.IsUpper(m.Value[0]) == true)
        {
            // Capitalize the replacement string
            // using System.Text;
            StringBuilder sb = new StringBuilder(replaceWith);
            sb[0] = (Char.ToUpper(sb[0]));
            return sb.ToString();
        }
        else
        {
            return replaceWith;
        }
    }
}

若要使用陣列標記法存取字串的個別字元,您可以使用 StringBuilder 物件,它會多載 [] 運算子以提供對其內部字元緩衝區的存取權。 您還可以使用 ToCharArray 方法,將字串轉換為字元陣列。 下列範例會使用 ToCharArray 建立陣列, 然後修改這個陣列中的一些元素, 再呼叫把字元陣列視為輸入參數的字串建構函式 (Constructor) 來建立新字串。

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);

        // Keep the console window open in debug mode
        System.Console.WriteLine("Press any key to exit.");
        System.Console.ReadKey();
    }
}
/* Output:
  The quick brown fox jumped over the fence
  The quick brown cat jumped over the fence 
*/

下列範例是在極少數的情況使用,亦即您可能想要藉由以類似於 C-Style 字元陣列方式,使用 unsafe 程式碼以就地修改字串。 在這個範例中,會示範如何使用 fixed 關鍵字以「就地」存取個別字元, 還會示範對字串執行不安全的作業時,由於 C# 編譯器會在內部儲存 (暫存) 字串,而可能會產生的一個副作用 (Side Effect)。 一般而言,除非有絕對的必要,否則不應使用此技巧。

class UnsafeString
{
    unsafe static void Main(string[] args)
    {
        // Compiler will store (intern) 
        // these strings in same location.
        string s1 = "Hello";
        string s2 = "Hello";

        // Change one string using unsafe code.
        fixed (char* p = s1)
        {
            p[0] = 'C';
        }

        //  Both strings have changed.
        Console.WriteLine(s1);
        Console.WriteLine(s2);

        // Keep console window open in debug mode.
        Console.WriteLine("Press any key to exit.");
        Console.ReadKey();
    }

}

請參閱

概念

C# 程式設計手冊

字串 (C# 程式設計手冊)