共用方式為


如何在 C 語言中修改字串內容#

本文展示了幾種透過修改現有 string來產生 的string技術。 所有示範的技術都會將修改結果作為一個新的 string 物件回傳。 為了證明原始字串與修改後的字串是不同的實例,範例將結果儲存在一個新的變數中。 你可以在執行每個範例時,檢視 string 原始和修改 string 後的新版本。

本文展示了幾項技術。 你可以替換現有的文字。 你可以搜尋模式,並用其他文字替換匹配的文字。 你可以把字串當作一串字元來處理。 你也可以使用方便的方法來去除留白。 選擇最符合你情境的技巧。

取代文字

以下程式碼透過將現有文字替換為其他內容來建立新字串。

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.TrimStartString.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) 方法將一個函數作為其參數之一,提供替換的邏輯。 在此範例中,該函數 是 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」的起始索引。接下來的三個字元則被換成不同的詞。 最後,從更新的字元陣列構造出一個新字串。

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 提供了一種 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);

你可以使用不安全的程式碼來修改固定區塊中的字串,但在建立字串後強烈不建議修改字串內容。 這樣做會導致不可預測的錯誤。 舉例來說,如果有人實習了一個內容和你一樣的字串,他們拿到你的副本,沒想到你會修改他們的字串。

另請參閱