物件 String 是不可變的。 每次您在 類別中使用 System.String 其中一個方法時,都會在記憶體中建立新的字串物件,這需要該新物件的新空間配置。 在您需要對字串執行重複修改的情況下,與建立新 String 對象相關聯的額外負荷可能代價高昂。 當您想要修改字串而不建立新的物件時,可以使用 類別 System.Text.StringBuilder 。 例如,在迴圈中串連許多字串時,使用 StringBuilder 類別可以提升效能。
匯入 System.Text 命名空間
類別 StringBuilder 位於 命名空間 System.Text 中。 若要避免在您的程式代碼中提供完整類型名稱,您可以匯入 System.Text 命名空間:
using System;
using System.Text;
Imports System.Text
創建 StringBuilder 物件
您可以將變數初始化為StringBuilder類別的其中一個多載建構函式,以建立新實例,如下列範例所示。
StringBuilder myStringBuilder = new StringBuilder("Hello World!");
Dim myStringBuilder As New StringBuilder("Hello World!")
設定容量和長度
StringBuilder雖然 是動態物件,可讓您擴充其封裝字串中的字元數,但您可以指定其可保存的最大字元數目值。 此值稱為 物件的容量,不應與目前 StringBuilder 保存的字串長度混淆。 例如,您可以使用長度為 5 的 StringBuilder 字串 「Hello」 建立 類別的新實例,而且您可以指定物件的最大容量為 25。 當您修改 StringBuilder時,它不會重新配置本身的大小,直到達到容量為止。 發生這種情況時,會自動配置新的空間,並將容量加倍。 您可以使用其中一個多載建構函式來指定 類別的 StringBuilder 容量。 下列範例指定 myStringBuilder
物件可以展開至最多 25 個空格。
StringBuilder myStringBuilder = new StringBuilder("Hello World!", 25);
Dim myStringBuilder As New StringBuilder("Hello World!", 25)
此外,您可以使用讀取/寫入 Capacity 屬性來設定物件的最大長度。 下列範例會使用 Capacity 屬性來定義物件長度上限。
myStringBuilder.Capacity = 25;
myStringBuilder.Capacity = 25
EnsureCapacity方法可用來檢查目前 StringBuilder 的容量。 如果容量大於傳遞的值,則不會進行任何變更;不過,如果容量小於傳遞的值,則目前的容量會變更為符合傳遞的值。
Length屬性也可以檢視或設定。 如果您將 Length 屬性設定為大於 Capacity 屬性的值, 則 Capacity 屬性會自動變更為與 Length 屬性相同的值。 將 Length 屬性設定為小於目前 StringBuilder 內字串長度的值會縮短字串。
修改 StringBuilder 字串
下表列出可用來修改 StringBuilder 內容的方法。
方法名稱 | 使用 |
---|---|
StringBuilder.Append | 將資訊附加至目前 StringBuilder 的結尾。 |
StringBuilder.AppendFormat | 以格式化文字取代傳入字串的格式規範。 |
StringBuilder.Insert | 將字串或物件插入目前 StringBuilder 的指定索引中。 |
StringBuilder.Remove | 從目前的 StringBuilder 中移除指定的字元數。 |
StringBuilder.Replace | 以另一個指定的字元或字串取代目前 StringBuilder 中所有出現的指定字元或字串。 |
添附
Append 方法可用來將物件的文字或字串表示加入至目前 StringBuilder 所表示之字串的結尾。 下列範例會將 StringBuilder 初始化為 「Hello World」,然後將某些文字附加至 對象的結尾。 空間會視需要自動分配。
StringBuilder myStringBuilder = new StringBuilder("Hello World!");
myStringBuilder.Append(" What a beautiful day.");
Console.WriteLine(myStringBuilder);
// The example displays the following output:
// Hello World! What a beautiful day.
Dim myStringBuilder As New StringBuilder("Hello World!")
myStringBuilder.Append(" What a beautiful day.")
Console.WriteLine(myStringBuilder)
' The example displays the following output:
' Hello World! What a beautiful day.
AppendFormat
該StringBuilder.AppendFormat方法將文字新增至StringBuilder物件的結尾。 它會呼叫要格式化的物件或對象的實作,以支援IFormattable。 因此,它會接受數值、日期和時間和列舉值的標準格式字串、數值和日期和時間值的自定義格式字串,以及針對自定義類型定義的格式字串。 (如需格式化的詳細資訊,請參閱 格式化類型。)您可以使用這個方法來自定義變數的格式,並將這些值附加至 StringBuilder。 下列範例會使用AppendFormat方法,將格式化為貨幣值的整數值放在StringBuilder物件的結尾。
int MyInt = 25;
StringBuilder myStringBuilder = new StringBuilder("Your total is ");
myStringBuilder.AppendFormat("{0:C} ", MyInt);
Console.WriteLine(myStringBuilder);
// The example displays the following output:
// Your total is $25.00
Dim MyInt As Integer = 25
Dim myStringBuilder As New StringBuilder("Your total is ")
myStringBuilder.AppendFormat("{0:C} ", MyInt)
Console.WriteLine(myStringBuilder)
' The example displays the following output:
' Your total is $25.00
插入
方法會將 Insert 字串或物件加入至目前 StringBuilder 物件中指定的位置。 下列範例會使用這個方法,將單字插入物件的第六個位置 StringBuilder 。
StringBuilder myStringBuilder = new StringBuilder("Hello World!");
myStringBuilder.Insert(6,"Beautiful ");
Console.WriteLine(myStringBuilder);
// The example displays the following output:
// Hello Beautiful World!
Dim myStringBuilder As New StringBuilder("Hello World!")
myStringBuilder.Insert(6, "Beautiful ")
Console.WriteLine(myStringBuilder)
' The example displays the following output:
' Hello Beautiful World!
刪除
您可以使用 Remove 方法,從指定的以零起始的索引,從目前 StringBuilder 物件中移除指定的字元數。 下列範例會使用 Remove 方法來縮短 StringBuilder 物件。
StringBuilder myStringBuilder = new StringBuilder("Hello World!");
myStringBuilder.Remove(5,7);
Console.WriteLine(myStringBuilder);
// The example displays the following output:
// Hello
Dim myStringBuilder As New StringBuilder("Hello World!")
myStringBuilder.Remove(5, 7)
Console.WriteLine(myStringBuilder)
' The example displays the following output:
' Hello
替換
Replace 方法可用來將 物件內的StringBuilder字元取代為另一個指定的字元。 下列範例會使用 Replace 方法來搜尋 StringBuilder 物件中的所有驚嘆號字元(!),並將它們替換為問號字元(?)。
StringBuilder myStringBuilder = new StringBuilder("Hello World!");
myStringBuilder.Replace('!', '?');
Console.WriteLine(myStringBuilder);
// The example displays the following output:
// Hello World?
Dim myStringBuilder As New StringBuilder("Hello World!")
myStringBuilder.Replace("!"c, "?"c)
Console.WriteLine(myStringBuilder)
' The example displays the following output:
' Hello World?
將 StringBuilder 物件轉換為字串
您必須先將 StringBuilder 對象 String 轉換成 物件,才能將 物件所表示的 StringBuilder 字串傳遞至具有 String 參數的方法,或將其顯示在使用者介面中。 您可以呼叫 StringBuilder.ToString 方法來執行這項轉換。 下列範例會呼叫數 StringBuilder 個方法,然後呼叫 StringBuilder.ToString() 方法來顯示字串。
using System;
using System.Text;
public class Example
{
public static void Main()
{
StringBuilder sb = new StringBuilder();
bool flag = true;
string[] spellings = { "recieve", "receeve", "receive" };
sb.AppendFormat("Which of the following spellings is {0}:", flag);
sb.AppendLine();
for (int ctr = 0; ctr <= spellings.GetUpperBound(0); ctr++) {
sb.AppendFormat(" {0}. {1}", ctr, spellings[ctr]);
sb.AppendLine();
}
sb.AppendLine();
Console.WriteLine(sb.ToString());
}
}
// The example displays the following output:
// Which of the following spellings is True:
// 0. recieve
// 1. receeve
// 2. receive
Imports System.Text
Module Example
Public Sub Main()
Dim sb As New StringBuilder()
Dim flag As Boolean = True
Dim spellings() As String = {"recieve", "receeve", "receive"}
sb.AppendFormat("Which of the following spellings is {0}:", flag)
sb.AppendLine()
For ctr As Integer = 0 To spellings.GetUpperBound(0)
sb.AppendFormat(" {0}. {1}", ctr, spellings(ctr))
sb.AppendLine()
Next
sb.AppendLine()
Console.WriteLine(sb.ToString())
End Sub
End Module
' The example displays the following output:
' Which of the following spellings is True:
' 0. recieve
' 1. receeve
' 2. receive