1、创建StringBuiler实例
1.1 用构造函数直接创建
StringBuilder MyStringBuilder = new StringBuilder("Hello World!");
1.2 创建空的实例再赋值
StringBuilder str = new StringBuilder();
Str.Append("Hello World!");
2、StringBuiler用法
2.1 Append(string Str )\Append(char c):连接字符串、字符
StringBuilder Str= new StringBuilder("Hello World!");
Str.Append("c");
结果为:Hello World!c
2.2 toString(): 得到字符串
StringBuilder Str= new StringBuilder("Hello World!");
Str.toString();
结果为:Hello World!
2.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: 十六进制格式。
2.4 insert(int offset, String str)/insert(int offset, Char c):在指定位置之前插入字符(串)
StringBuilder Str= new StringBuilder("Hello World!");
Str.Insert(6,"cute ");
结果为:Hello cute World!
2.5 Remove(int offset,int length) 移除指定位置开始的指定长度的字符(串)
StringBuilder Str= new StringBuilder("Hello World!");
Str.Insert(6,"cute ");
Str.Remove(6, 4);
结果为:Hello World!
2.6 Replace (string str,string str2)将str替换成str2
StringBuilder Str= new StringBuilder("Hello World!");
Str.Replace("World","China");
结果为:Hello China!