StringBuilder 類存在的理由是: 在對字串增刪改時, 比 string 類更快; 更快的原因是無須像 string 一樣反覆地釋放和重建.
但它會在需要時重新分配記憶體, 如果把需要的記憶體預製好, 它會更快.
StringBuilder 的屬性與方法:
/* 屬性 */Capacity; // 容量; 可讀寫, 也可在構建時設定, 但改寫時使用 EnsureCapacity() 更保險Length; // 長度; 可讀寫, 寫入 0 時, 同 Clear(); Length
建構函式的 6 種重載:
using System.Text; // StringBuilder 所屬的命名空間 protected void Button1_Click(object sender, EventArgs e){ string str = ""; /* 無參時, Capacity 預設 16 */ StringBuilder sb1 = new StringBuilder(); str += sb1.Capacity.ToString("Capacity: #\n"); //Capacity: 16 /* 構建時指定 Capacity 大小 */ StringBuilder sb2 = new StringBuilder(11); str += sb2.Capacity.ToString("Capacity: #\n"); //Capacity: 11 /* 使用字串構建時, 如果字串 Length > 16, 其 Capacity 同字串的長度 */ StringBuilder sb3 = new StringBuilder("abcdefghijklmnopqrstuvwxyz"); str += sb3.Capacity.ToString("Capacity: #\n"); //Capacity: 26 /* 指定 Capacity 和 MaxCapacity */ StringBuilder sb4 = new StringBuilder(4, 10); str += sb4.Capacity.ToString("Capacity: #\t"); //Capacity: 4 sb4.Append("1234567890"); str += sb4.Capacity.ToString("Capacity: #\n"); //Capacity: 10 try { sb4.Append("ABC"); } catch (Exception err) { str += err.Message + "\n"; } //容量小於當前大小... /* 用字串構建, 同時指定 Capacity */ StringBuilder sb5 = new StringBuilder("1234567890", 32); str += string.Format("Capacity: {0}\tLength: {1}\n", sb5.Capacity, sb5.Length); //Capacity: 32 Length: 10 /* 從字串截取構建, 同時指定 Capacity */ StringBuilder sb6 = new StringBuilder("ABCDEFG", 1, 3, 12); str += string.Format("\"{0}\"\tCapacity: {1}\tLength: {2}", sb6, sb6.Capacity, sb6.Length); //"BCD"Capacity: 12Length: 3 TextBox1.Text = str;}
練習:
//ToString()protected void Button1_Click(object sender, EventArgs e){ StringBuilder sb = new StringBuilder("1234567890"); string s1 = sb.ToString(); //1234567890 string s2 = sb.ToString(2, 3); //345 TextBox1.Text = s1 + "\n" + s2;}//Append()、AppendFormat()、AppendLine()protected void Button2_Click(object sender, EventArgs e){ StringBuilder sb = new StringBuilder(256); sb.Append("abcdefg"); sb.AppendLine(); sb.Append(3.1415926); sb.AppendLine(); sb.AppendFormat("{0:#.##}", 3.1415926); TextBox1.Text = sb.ToString();/*abcdefg3.14159263.14*/}//Insert()、Remove()、Replace()protected void Button3_Click(object sender, EventArgs e){ StringBuilder sb = new StringBuilder("..........", 256); string s1 = sb.Insert(2, "ABC").ToString(); //..ABC........ string s2 = sb.Insert(2, 3.14).ToString(); //..3.14ABC........ string s3 = sb.Remove(6, 3).ToString(); //..3.14........ string s4 = sb.Replace('.', '*').ToString(); //**3*14******** TextBox1.Text = s1 + "\n" + s2 + "\n" + s3 + "\n" + s4;}//CopyToprotected void Button4_Click(object sender, EventArgs e){ string str = ".........."; char[] cArr = str.ToCharArray(); StringBuilder sb = new StringBuilder("1234567890"); sb.CopyTo(2, cArr, 0, 3); TextBox1.Text = new string(cArr); //345.......}