Tip
本文屬於 基礎部分, 適合已經至少懂一種程式語言並正在學習 C# 的開發者。 如果你是程式新手,建議先從 入門 教學開始。
來自另一種語言? 像 Java 和 JavaScript 一樣,C# 字串是不可變的:像 和 Replace 這類方法Trim會回傳新字串,而不是更改原本的字串。 這裡的模式與那些語言中的 String 方法相對應。
C# string 是 不變的,也就是說,建立後內容永遠不會改變。 每個看似會修改字串的方法,實際上都會回傳一個已套用變更的新 string,而原始字串則維持不變。 本文的範例會將每個結果儲存在一個新變數中,讓你同時看到來源值和修改後的值。
選擇符合你情境的技巧:替換已知文字、裁掉空白、移除一段字元、替換符合模式的文字,或編輯單一字元。
替換已知文本
此 String.Replace 方法每次出現一個字串時,都會用另一個字串替換,並將結果以新字串的形式回傳:
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 還有一個過載機制,會切換單一角色。 以下範例將每個空格都換成底線:
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.
這兩種過載都會替換 串中所有 的配對,而不只是第一個。 無論你傳遞單一字元還是字串, Replace 都會在一次呼叫中替換所有出現的情況。
修剪空格符
使用 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# 中的搜尋字串。 關於正則表達式語法,請參見 正則表達式語言快速參考。
修改個別字元
若要依位置更改字元,先將字串複製到 a Span<T> 字元組,修改 span,然後從中建立新字串。 以下範例會尋找「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.
對於避免中間配置的高效能情境,執行時會提供較低階的 API,例如 String.Create。 這些技術都很先進;對於日常程式碼,本文中的方法是正確的選擇。