StringBuilder位于命名空间System.Text下,使用前需引入
using System.Text;
StringBuilder的构造
new StringBuilder(string value)
StringBuilder sb1 = new StringBuilder("www.abc.com");
利用构造函数创建一个值为“www.abc.com”的StringBuilder对象
new StringBuilder(int capacity)
StringBuilder sb2 = new StringBuilder(10);
创建一个空的StringBuilder对象,容量为10个字符
new StringBuilder(string value,int capacity)
StringBuilder sb3 = new StringBuilder("www.abc.com",10);
创建一个默认值为“www.abc.com”,容量为10个字符的StringBuilder对象
ps:当StringBuilder中的值超过其容量时,StringBuilder会申请一个容量为原来两倍的内存区域并将原有值和新增值拷贝到这一新内存区域,然后回收旧的内存区域
StringBuilder sb = new StringBuilder("abc", 4);
Console.WriteLine(sb.Capacity); //4
sb.Append("def");
Console.WriteLine(sb.Capacity); //8
String和StringBuilder的区别
以在“www.abc.com”后拼接“/123.html”为例
String:
string s = "www.abc.com";
s += "/123.html";
Console.WriteLine(s);
String需要创建一个新的内存区域用于存储拼接后的值并将应用指向新的内存区域,然后回收旧的内存区域
StringBuilder:
StringBuilder sb = new StringBuilder("www.abc.com", 25);
sb.Append("/123.html");
Console.WriteLine(sb.ToString());
StringBuilder直接在当前内存区域中进行拼接操作,而无需创建新的内存区域(前提是容量足够大)
总结:当需要对字符串频繁进行操作时,StringBuilder效率较高
StringBuilder的方法
1.StringBuilder.Append(string value):在末尾追加新的字符串
StringBuilder sb = new StringBuilder("www.abc.com");
sb.Append("/123.html"); //www.abc.com/123.html
2.StringBuilder.Insert(int index,string value):在特定位置插入新的字符串
StringBuilder sb = new StringBuilder("www.abc.com");
sb.Insert(0, "http://"); //http://www.abc.com
3.StringBuilder.Remove(int startIndex,int length):从当前字符串中删除特定字符串
StringBuilder sb = new StringBuilder("www.abc.com");
sb.Remove(0, 4); //abc.com
4.StringBuilder.Replace(char oldChar,char newChar):替换当前字符串中所有特定字符
StringBuilder sb = new StringBuilder("www.abc.com");
sb.Replace('b','x'); //www.axc.com
5.StringBuilder.ToString():将StringBuilder中的值转换为不可变的字符串