方法 : 文字列の内容を変更する (C# プログラミング ガイド)

更新 : 2008 年 7 月

文字列は変更不可であるため、(アンセーフ コードを使用しない限り) 文字列オブジェクトを作成した後、その値は変更できません。ただし、文字列の値を変更し、その結果を新しい文字列オブジェクトに格納する方法は数多くあります。System.String クラスには、入力文字列を操作し、新しい文字列オブジェクトを返すメソッドが用意されています。多くの場合、元の文字列を格納している変数に新しいオブジェクトを代入できます。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 を使用して配列を作成しています。その後、この配列の要素の一部を変更しています。さらに、入力パラメータとして文字配列を受け取る文字列コンストラクタを呼び出して、新しい文字列を作成しています。

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 スタイルの文字配列と同様の方法でアンセーフ コードを使用して埋め込み文字列を変更する、非常にまれな場合のために用意したものです。この例では、fixed キーワードを使用して "埋め込まれている" 個々の文字にアクセスする方法を示します。また、文字列に対しアンセーフ操作を実行すると発生する可能性のある副作用を示します。この副作用の原因は、C# コンパイラが文字列を内部に格納する (保持する) 方法です。通常、この方法は、特に必要な場合以外は使用しないでください。

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# プログラミング ガイド)

変更履歴

日付

履歴

理由

2008 年 7 月

多くの部分を変更し、またコード例を追加し、内容の正確性および完全性を改善

コンテンツ バグ修正