stringBuilder类的一些用法


对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!

 


免责声明!

本站转载的文章为个人学习借鉴使用,本站对版权不负任何法律责任。如果侵犯了您的隐私权益,请联系本站邮箱yoyou2525@163.com删除。



 
粤ICP备18138465号  © 2018-2025 CODEPRJ.COM