System.Text.StringBuilder类处理…
来源:互联网 发布:淘宝客服回复大全 编辑:程序博客网 时间:2024/04/29 06:08
String 对象是不可变的。 每次使用 System. String类中的一个方法时,都要在内存中创建一个新的字符串对象,这就需要为该新对象分配新的空间。在需要对字符串执行重复修改的情况下,与创建新的String 对象相关的系统开销可能会非常大。 如果要修改字符串而不创建新的对象,则可以使用System.Text. StringBuilder类。例如,当在一个循环中将许多字符串连接在一起时,使用 StringBuilder 类可以提升性能。
1.设置容量和长度:
虽然 StringBuilder是动态对象,允许扩充它所封装的字符串中的字符数,但您可以通过一个值来指定该对象可容纳的最大字符数。此值称为该对象的容量,不要将它与当前 StringBuilder 所容纳的字符串的长度相混淆。 例如,可以使用长度为 5的字符串“Hello”创建 StringBuilder 类的一个新实例,同时可以指定该对象的最大容量为 25。 当修改StringBuilder 时,在达到容量之前,该对象不会为自己重新分配空间。当达到容量时,将自动分配新的空间且容量翻倍。 可以使用重载的构造函数之一来指定 StringBuilder 类的容量。 下面的示例指定可以将MyStringBuilder 对象扩充到最大 25 个空白。
StringBuilder MyStringBuilder = new StringBuilder("Hello World!", 25);
或使用Capacity属性:MyStringBuilder.Capacity = 25;
2.修改 StringBuilder 字符串:
int MyInt = 25;
StringBuilder MyStringBuilder = new StringBuilder("Your total is ");
MyStringBuilder.AppendFormat("{0:C} ", MyInt);Console.WriteLine(MyStringBuilder);
// The example displays the following output:// Your total is $25.00
StringBuilder MyStringBuilder = new StringBuilder("Hello World!");
MyStringBuilder.Replace('!', '?');
Console.WriteLine(MyStringBuilder);
// The example displays the following output:// Hello World?
3.将 StringBuilder 对象转换为 String
public class Example{ public static void Main()
{
StringBuilder sb = new StringBuilder();
bool flag = true;
string[] spellings = { "recieve", "receeve", "receive" };
sb.AppendFormat("Which of the following spellings is {0}:", flag);
sb.AppendLine();
for (int ctr = 0; ctr <= spellings.GetUpperBound(0); ctr++)
{
sb.AppendFormat(" {0}. {1}", ctr, spellings[ctr]);
sb.AppendLine(); } sb.AppendLine();
Console.WriteLine(sb.ToString()); }}
// The example displays the following output:
// Which of the following spellings is True:
// 0. recieve
// 1. receeve
// 2. receive
注:本文部分源于VS 2012帮助文档。
0 0
- System.Text.StringBuilder类处理…
- System.Text.StringBuilder 类
- System.Text.StringBuilder 类
- System.Text.StringBuilder拼装table
- System.Text.StringBuilder 和System.String
- System.String和System.Text.StringBuilder
- system.string 和System.Text.StringBuilder的不同
- system.string 和 System.Text.StringBuilder的不同
- 学习笔记-- 使用System.Text.StringBuilder的方法和属性
- System::Text::StringBuilder::AppendFormat' : no overloaded function takes 7 arguments
- StringBuffer类,StringBuilder类和System类
- 追赶微软StringBuilder,类似StringBuilder的字符串处理类
- 类似于StringBuilder的字符串加强处理类
- 类似于StringBuilder的字符串加强处理类
- java字符串处理--String,StringBuffer,StringBuilder类
- The System.Text Namespace
- System.Text命名空间
- System.Text.Encoding 简介
- 制图综合的方根模型(开方根规律)
- 博客十年,感谢有你!
- CorelDRAW中线要素自动闭合错误解…
- ArcGIS属性表关联方式(Join和Rela…
- 线要素综合算法
- System.Text.StringBuilder类处理…
- CodeForces 609B The Best Gift
- C# 测试代码段性能耗时
- 转:SqlBulkCopy批量复制数据
- C# DataGridView使用代码
- R语言制作箱型图
- Matlab绘制箱线图
- 传智HTML基础1-3课笔记
- icegrid 学习