StringBuilder是在using System.Text命名空间下的一个成员。
在做字符串拼接的时候,因为字符串是引用类型,新的字符串是会再内存中创建的,所以用+号拼接字符串是比较耗效率的. StringBuilder类就可以提高性能。
StringBuilder与字符串很多的方法相同,下面列举的是字符串没有的
- EnsureCapacity //指定StringBuilder实例一个最小的容量
- Append //添加新字符串到StringBuilder实例的末尾
- AppendFormat //格式化添加的字符串
- toString //将StringBuilder实例转化为字符串
EnsureCapacity(设置字符串的容量)
StringBuilder str1 = new StringBuilder("",);
StringBuilder str2 = new StringBuilder("");
str2.EnsureCapacity();
Append (添加)
StringBuilder str1 = new StringBuilder();
str1.Append("OK");
Console.WriteLine(str1);
AppendFormat(格式化添加的字符串)
StringBuilder str1 = new StringBuilder();
str1.AppendFormat("Good Student :,{0},{1},{2},{3},{4}!!!!","Tim","Jack","Ralf","Aler","Lily");
Console.WriteLine(str1); Result: Good Student:Tim,Jack,Ralf,Aler,Lily
toString (转化为字符串)
StringBuilder str1 = new StringBuilder();
str1.Append("Tim-");
str1.Append("Jack");
Console.WriteLine(str1.toString());
result: Tim-Jack