Tip
この記事は、少なくとも 1 つのプログラミング言語を既に知っており、C# を学習している開発者向けの 基礎 セクションの一部です。 プログラミングを初めて使用する場合は、最初に「 はじめ に」チュートリアルから始めてください。
別の言語から来ていますか? Javaや JavaScript と同様に、C# 文字列は不変です。ReplaceやTrimなどのメソッドは、元の文字列を変更するのではなく、新しい文字列を返します。 ここでのパターンは、これらの言語のメソッド String 並列です。
C# string は 不変です。つまり、作成後にその内容が変更されることはありません。 文字列を変更するように見えるすべてのメソッドは、実際には変更を伴う新しい string を返し、元の変更はそのまま残します。 この記事の例では、ソースと変更された値の両方を確認できるように、各結果を新しい変数に格納します。
シナリオに一致する手法を選択します。既知のテキストの置換、空白のトリミング、文字の範囲の削除、パターンに一致するテキストの置換、個々の文字の編集を行います。
既知のテキストを置き換える
String.Replace メソッドは、1 つの文字列が出現するたびに別の文字列に置き換え、結果を新しい文字列として返します。
string source = "The mountains are behind the clouds today.";
// Replace returns a new string; the original is unchanged.
string updated = source.Replace("mountains", "peaks");
Console.WriteLine(source);
// => The mountains are behind the clouds today.
Console.WriteLine(updated);
// => The peaks are behind the clouds today.
元の文字列は変更されず、不変性を示します。 Replace 置換を使用して新しい文字列を作成します。
Replace には、1 文字をスワップするオーバーロードもあります。 次の例では、すべてのスペースをアンダースコアに置き換えます。
string source = "The mountains are behind the clouds today.";
// Replace every occurrence of one character with another.
string updated = source.Replace(' ', '_');
Console.WriteLine(updated);
// => The_mountains_are_behind_the_clouds_today.
どちらのオーバーロードも、文字列内のすべての一致箇所を置き換え、最初の一致箇所だけを置き換えるわけではありません。 1 文字を渡す場合でも文字列を渡す場合でも、 Replace は 1 回の呼び出しですべての出現箇所を置き換えます。
空白をトリミングする
先頭または末尾の空白を削除するには、 String.Trim、 String.TrimStart、および String.TrimEnd を使用します。 各メソッドは、新しい文字列を返します。
string source = " I'm wider than I need to be. ";
// Each method returns a new string with whitespace removed.
Console.WriteLine($"<{source.Trim()}>");
// => <I'm wider than I need to be.>
Console.WriteLine($"<{source.TrimStart()}>");
// => <I'm wider than I need to be. >
Console.WriteLine($"<{source.TrimEnd()}>");
// => < I'm wider than I need to be.>
一定範囲の文字を削除する
String.Remove メソッドは、インデックスから始まる文字数を削除します。 それを String.IndexOf と組み合わせて、削除するテキストを見つけます。
string source = "Many mountains are behind many clouds today.";
string toRemove = "many ";
// Find the text, then remove that span by index and length.
int index = source.IndexOf(toRemove);
string result = index >= 0
? source.Remove(index, toRemove.Length)
: source;
Console.WriteLine(result);
// => Many mountains are behind clouds today.
パターンに一致するテキストを置き換える
正確な文字列ではなくパターンに従うテキストを置き換える必要がある場合は、 正規表現を使用します。
Regex.Replace メソッドは、各置換を計算する関数を受け入れるため、元の大文字と小文字などの詳細を保持できます。
the\s パターンは、"the" の後に空白文字が続き、"there" と一致しないようにします。
string source = "The mountains are still there behind the clouds today.";
// Replace "the" or "The" followed by whitespace, preserving the original case.
// The \s in the pattern keeps "there" from matching.
string result = Regex.Replace(
source,
"""the\s""",
match => char.IsUpper(match.Value[0]) ? "Many " : "many ",
RegexOptions.IgnoreCase);
Console.WriteLine(result);
// => Many mountains are still there behind many clouds today.
置換ではなくパターンベースの検索については、「 C# での文字列の検索」を参照してください。 正規表現の構文については、「 正規表現言語のクイック リファレンス」を参照してください。
個々の文字を変更する
位置によって文字を変更するには、文字列を文字の Span<T> にコピーし、スパンを変更してから、そこから新しい文字列を作成します。 次の例では、"fox" という単語を検索し、それを "cat" に置き換えます。
string phrase = "The quick brown fox jumps over the fence.";
// A string is immutable, so copy it into a Span<char> to edit in place.
Span<char> characters = stackalloc char[phrase.Length];
phrase.CopyTo(characters);
int index = phrase.IndexOf("fox");
if (index != -1)
{
characters[index] = 'c';
characters[index + 1] = 'a';
characters[index + 2] = 't';
}
// Build a new string from the modified characters.
string updated = new string(characters);
Console.WriteLine(updated);
// => The quick brown cat jumps over the fence.
中間割り当てを回避する高パフォーマンスのシナリオでは、ランタイムは、 String.Createなどの下位レベルの API を提供します。 これらの手法は高度です。日常のコードでは、この記事のメソッドが適切な選択肢です。
こちらも参照ください
.NET