|
StringBuilder 類型提供了一系列方法來處理字串,這些方法讓你可以動態地建立、修改和處理字串。以下是 StringBuilder 的一些常用屬性和方法:
常見屬性
- Capacity:
取得或設定 StringBuilder 目前的容量,即它可以容納的字符數量。
Capacity |
//初始容量為 10
StringBuilder sb = new StringBuilder("Hello", 10);
Console.WriteLine($"Capacity: {sb.Capacity}"); //輸出:Capacity: 10
|
- Length:
取得或設定 StringBuilder 目前的長度,即它包含的字符數量。
Length |
StringBuilder sb = new StringBuilder("Hello world");
// 輸出:Length before: 11
Console.WriteLine($"Length before: {sb.Length}");
sb.Length = 5; // 截斷到 5 個字符
Console.WriteLine(sb.ToString()); // 輸出:Hello
|
常見方法
- Append():
將指定的字串或字符追加到 StringBuilder 的末尾。
Append |
StringBuilder sb = new StringBuilder();
sb.Append("Hello");
sb.Append(' ');
sb.Append("world");
Console.WriteLine(sb.ToString());//輸出:Hello world
|
- AppendFormat():
使用指定的格式將字串插入到 StringBuilder 的末尾。
AppendFormat |
StringBuilder sb = new StringBuilder();
sb.AppendFormat("Name: {0}, Age: {1}", "John", 30);
Console.WriteLine(sb.ToString()); //輸出:Name: John, Age: 30
|
- Insert():
將指定的字串或字符插入到 StringBuilder 中的指定位置。
Insert |
StringBuilder sb = new StringBuilder("Hello world");
sb.Insert(5, "beautiful ");
//輸出:Hello beautiful world
Console.WriteLine(sb.ToString());
|
- Remove():
從 StringBuilder 中刪除指定位置的一定數量的字符。
Remove |
StringBuilder sb = new StringBuilder("Hello world");
sb.Remove(5, 7); // 從索引 5 開始,刪除 7 個字符
Console.WriteLine(sb.ToString()); // 輸出:Hello
|
- Replace():
將 StringBuilder 中指定範圍內的字串替換為指定的字串。
Replace |
StringBuilder sb = new StringBuilder("Hello world");
sb.Replace("world", "Universe");
Console.WriteLine(sb.ToString()); //輸出:Hello Universe
|
- Clear():
清除 StringBuilder 中的所有字符。
Clear |
StringBuilder sb = new StringBuilder("Hello world");
sb.Clear();
Console.WriteLine(sb.ToString()); //輸出:
|
- ToString():
將 StringBuilder 中的內容轉換為一個字串。
ToString |
StringBuilder sb = new StringBuilder("Hello world");
string result = sb.ToString();
Console.WriteLine(result); //輸出:Hello world
|
|