對String對象進行處理的時候比如拼接、截取,會在內存中新建很多字符串對象。為了減少內存開支,可以使用StringBuilder類型。
創建StringBuiler實例:
用構造函數直接創建:
StringBuilder MyStringBuilder = new StringBuilder("Hello World!");
或創建空的實例再賦值;
StringBuilder MyStringBuilder = new StringBuilder(); Str.Append("Hello World!");
1、Append(string Str )\Append(char c):連接字符串、字符:
StringBuilder Str= new StringBuilder("Hello World!"); Str.Append("c");
得到:Hello World!c
2、toString():得到字符串:
StringBuilder Str= new StringBuilder("Hello World!"); Str.toString();
得到 Hello World!
3、AppendFormat() 可以使用此方法來自定義變量的格式並將這些值追加到 StringBuilder 的后面
StringBuilder Str= new StringBuilder("Hello World!"); Str.AppendFormat("{0:C}", 10);
得到: Hello World!¥10.00
補充:{0:c} "0"表示占位符。c 是格式化控制信息,c表示貨幣格式。
c | C:代表貨幣格式
d | D:代表十進制格式
e | E:代表科學計數(指數)格式
f | F: 浮點格式
x | X: 十六進制格式。
4、insert(int offset, String str)/insert(int offset, Char c):在指定位置之前插入字符(串)
StringBuilder Str= new StringBuilder("Hello World!"); Str.Insert(6,"cute ");
得到:Hello cute World!
5、Remove(int offset,int length) 移除指定位置開始的指定長度的字符(串):
StringBuilder Str= new StringBuilder("Hello World!"); Str.Insert(6,"cute "); Str.Remove(6, 4);
得到 Hello World!
6、Replace (string str,string str2)將str替換成str2:
StringBuilder Str= new StringBuilder("Hello World!"); Str.Replace("World","China");
得到:Hello China!