C# で文字列の内容を変更する方法

この記事では、既存の string を変更して string を生成するためのいくつかの手法を示します。 紹介するすべての手法で、変更の結果が string オブジェクトとして返されます。 元と変更後の文字列が異なるインスタンスであることを示すために、例では、新しい変数に結果が格納されています。 各例を実行するとき、元の string と変更後の新しい string を調べることができます。

注意

この記事の C# 例は、Try.NET インライン コード ランナーとプレイグラウンドで実行されます。 [実行] ボタンを選択すると、対話型ウィンドウで例が実行されます。 コードを実行したら、コードを変更し、 [実行] をもう一度選択して変更後のコードを実行できます。 変更後のコードが対話型ウィンドウで実行されるか、コンパイルできなかった場合、対話型ウィンドウにすべての C# コンパイラ エラー メッセージが表示されます。

この記事ではいくつかの手法を示します。 既存のテキストは置き換えることができます。 パターンを検索して、一致するテキストを他のテキストに置き換えることができます。 文字列は、一連の文字として扱うことができます。 空白を削除する便利なメソッドも使用できます。 シナリオに最も近い手法を選択してください。

テキストの置換

次のコードでは、既存のテキストを代替のテキストと置き換えることで新しい文字列が作成されます。

string source = "The mountains are behind the clouds today.";

// Replace one substring with another with String.Replace.
// Only exact matches are supported.
var replacement = source.Replace("mountains", "peaks");
Console.WriteLine($"The source string is <{source}>");
Console.WriteLine($"The updated string is <{replacement}>");

先のコードは、文字列のこの不変プロパティを示しています。 先の例では、元の文字列 source が変更されていないことがわかります。 String.Replace メソッドによって、変更を含む新しい string が生成されます。

Replace メソッドは、文字列または単一の文字のどちらかを置き換えることができます。 どちらの場合も、検索で見つかったすべてのテキストが置き換えられます。 次の例では、すべての ' ' の文字が '_' に置き換えられます。

string source = "The mountains are behind the clouds today.";

// Replace all occurrences of one char with another.
var replacement = source.Replace(' ', '_');
Console.WriteLine(source);
Console.WriteLine(replacement);

ソース文字列は変更されず、置き換えられた新しい文字列が返されます。

空白のトリミング

String.TrimString.TrimStart、および String.TrimEnd メソッドを使用して、先頭または末尾の空白を削除することができます。 次のコードは、それぞれの例を示しています。 ソース文字列は変更されません。これらのメソッドは、変更した内容を含む新しい文字列を返します。

// Remove trailing and leading white space.
string source = "    I'm wider than I need to be.      ";
// Store the results in a new string variable.
var trimmedResult = source.Trim();
var trimLeading = source.TrimStart();
var trimTrailing = source.TrimEnd();
Console.WriteLine($"<{source}>");
Console.WriteLine($"<{trimmedResult}>");
Console.WriteLine($"<{trimLeading}>");
Console.WriteLine($"<{trimTrailing}>");

テキストの削除

String.Remove メソッドを使用して文字列からテキストを削除することができます。 このメソッドによって、特定のインデックスから始まる文字が削除されます。 次の例は、String.IndexOf とそれに続く Remove を使用して文字列からテキストを削除する方法を示しています。

string source = "Many mountains are behind many clouds today.";
// Remove a substring from the middle of the string.
string toRemove = "many ";
string result = string.Empty;
int i = source.IndexOf(toRemove);
if (i >= 0)
{
    result= source.Remove(i, toRemove.Length);
}
Console.WriteLine(source);
Console.WriteLine(result);

一致パターンの置換

正規表現を使用すると、テキスト一致パターンを新しいテキストに置き換えることができます (パターンで定義されている場合もあります)。 次の例では、System.Text.RegularExpressions.Regex クラスを使用してソース文字列でパターンを検索し、適切な大文字と小文字に置き換えています。 Regex.Replace(String, String, MatchEvaluator, RegexOptions) メソッドは、置換のロジックをその引数の 1 つとして提供する機能を受け取ります。 この例で、関数 LocalReplaceMatchCase は、サンプル メソッド内で宣言されたローカル関数です。 LocalReplaceMatchCase は、System.Text.StringBuilder クラスを使用して大文字と小文字が適切な置換文字列を作成します。

正規表現は、既知のテキストよりもパターンに従ったテキストを検索して置き換える場合に特に役立ちます。 詳細については、「文字列を検索する方法」を参照してください。 検索パターン "the\s" は、単語 "the" とその後の空白文字を検索します。 パターンのこの部分により、ソース文字列の "there" は一致しなくなります。 正規表現言語要素の詳細については、「正規表現言語 - クイック リファレンス」をご覧ください。

string source = "The mountains are still there behind the clouds today.";

// Use Regex.Replace for more flexibility.
// Replace "the" or "The" with "many" or "Many".
// using System.Text.RegularExpressions
string replaceWith = "many ";
source = System.Text.RegularExpressions.Regex.Replace(source, "the\\s", LocalReplaceMatchCase,
    System.Text.RegularExpressions.RegexOptions.IgnoreCase);
Console.WriteLine(source);

string LocalReplaceMatchCase(System.Text.RegularExpressions.Match matchExpression)
{
    // Test whether the match is capitalized
    if (Char.IsUpper(matchExpression.Value[0]))
    {
        // Capitalize the replacement string
        System.Text.StringBuilder replacementBuilder = new System.Text.StringBuilder(replaceWith);
        replacementBuilder[0] = Char.ToUpper(replacementBuilder[0]);
        return replacementBuilder.ToString();
    }
    else
    {
        return replaceWith;
    }
}

StringBuilder.ToString メソッドによって、StringBuilder オブジェクトの内容と不変の文字列が返されます。

各文字の変更

文字列から文字配列を生成し、配列の内容を変更して、変更された配列の内容から新しい文字列を作成できます。

次の例は、文字列の文字のセットを置き換える方法を示しています。 最初に、String.ToCharArray() メソッドを使用して文字の配列が作成されます。 IndexOf メソッドを使用して "fox" という単語の開始インデックスを検索します。次の 3 つの文字が、別の単語に置き換えられます。 最後に、新しい文字列が更新された文字配列から構築されます。

string phrase = "The quick brown fox jumps over the fence";
Console.WriteLine(phrase);

char[] phraseAsChars = phrase.ToCharArray();
int animalIndex = phrase.IndexOf("fox");
if (animalIndex != -1)
{
    phraseAsChars[animalIndex++] = 'c';
    phraseAsChars[animalIndex++] = 'a';
    phraseAsChars[animalIndex] = 't';
}

string updatedPhrase = new string(phraseAsChars);
Console.WriteLine(updatedPhrase);

プログラムによって文字列の内容を作成する

文字列は不変なので、これまでの例ではすべて、一時的な文字列または文字の配列を作成しています。 ハイパフォーマンスのシナリオでは、これらのヒープの割り当てを回避することが望ましい場合があります。 .NET Core では String.Create メソッドを提供しており、中間の一時的な文字列の割り当てを回避しながら、コールバックを介してプログラムによって文字列の文字の内容を入力できます。

// constructing a string from a char array, prefix it with some additional characters
char[] chars = { 'a', 'b', 'c', 'd', '\0' };
int length = chars.Length + 2;
string result = string.Create(length, chars, (Span<char> strContent, char[] charArray) =>
{
    strContent[0] = '0';
    strContent[1] = '1';
    for (int i = 0; i < charArray.Length; i++)
    {
        strContent[i + 2] = charArray[i];
    }
});

Console.WriteLine(result);

アンセーフ コードを使用して固定ブロック内の文字列を変更することは可能ですが、文字列が作成された後に文字列の内容を変更することは強くお勧めしません。 そうすると、予期できない方法で中断が発生します。 たとえば、誰かがあなたの文字列と同じ内容の文字列をインターン処理する場合、その人はあなたのコピーを取得し、あなたが文字列を変更しようとしているとは想定しません。

関連項目