【C#】StringBuilder和string对比
2016-07-17 20:36
435 查看
StringBuilder对小编来说是一个非常新的概念,所以小编先来认识一下这个全新的内容StringBuilder。StringBuilder类在C#中一般被用来拼接字符串,依托.NET Framework可以实现添加替换移除等灵活的动态字符串操作。在.NET Framework中使用StringBuilder类来串联字符串。代码使用 StringBuilder 类的 Append 方法来串联字符串,因此不会有
+ 运算符的链接作用产生。
效果图
分配空间的例子
大多数的情况从性能比较:StringBuilder>String。
+ 运算符的链接作用产生。
StringBuilder使用方法
毕竟是第一次接触StringBuilder类所以解释一下具体的使用方法吧,这些东西相对来理论时还是代码来的更快一些。<span style="font-family:KaiTi_GB2312;font-size:24px;"><span style="font-family:KaiTi_GB2312;font-size:24px;">class Program { static void Main(string[] args) { //实例化StringBuilder对象 StringBuilder sb = new StringBuilder("Hello World!"); //Append //将信息追加到当前StringBuilder的结尾 sb.Append("I want to fly higher."); Console.WriteLine(sb); //AppendFormat //用带格式文本替换字符串中传递的格式说明符。 StringBuilder sbAppendFormat = new StringBuilder("Your total is "); sbAppendFormat.AppendFormat("{0}", "25yuan"); Console.WriteLine(sbAppendFormat); //Insert //将字符串或对象插入到当前 StringBuilder 对象的指定索引处。 StringBuilder sbInsert = new StringBuilder("Hello World!"); sbInsert.Insert(6, "Beautiful"); Console.WriteLine(sbInsert); //Remove //从当前 StringBuilder 对象中移除指定数量的字符。 StringBuilder sbRemove = new StringBuilder("Hello World!"); sbRemove.Remove(5, 7); Console.WriteLine(sbRemove); //Replace //替换指定索引处的指定字符。 StringBuilder sbReplace = new StringBuilder("Hello World!"); sbReplace.Replace('!', '?'); Console.WriteLine(sbReplace); Console.ReadKey(); } }</span></span>
效果图
设置容量和长度
虽然StringBuilder是动态对象,允许扩充它所封装的字符串中的字符数。但是可以通过一个值来指定对象的最大字符数。这个值称为该对象的容量。修改StringBulider时,在达到容量之前,对象不会重新给自己分配空间。到达容量是,将自动分配新的空间且容量翻倍。分配空间的例子
<span style="font-family:KaiTi_GB2312;font-size:24px;">StringBuilder sb = new StringBuilder("Hello World!", 25); //该对象可以存放到25个字符串</span>可以使用读/写 Capacity 属性来设置对象的最大长度
<span style="font-family:KaiTi_GB2312;font-size:24px;">sb.Capacity = 25;</span>
String和StringBulider区别
String 对象是不可变的。每次使用system.string类中的一个方法时,都要在内容中创建一个新的字符串对象,需要重新为新对象分配新的空间。在需要对字符串执行重复修改的情况下,与创建新的string对象相关的系统开销可能会变的很大。如果要修改字符串而不创建新的对象,使用StringBuilder类,循环中将许多字符串连接在一起的时,使用StringBuilder类会提高性能。大多数的情况从性能比较:StringBuilder>String。
总结
最近一直在使用StringBulider类,利用其拼接字符串,实现界面上根据后台数据动态显示内容,相对于之前使用的String利用运算符+实现字符串的拼接,真是效果不知道好多少。所以以后在当自己要的事情很麻烦的时候,可以尝试一下是否有更有的方法解决。相关文章推荐
- Junit测试【2】(详解suit函数)
- org.hibernate.loader.custom.NonUniqueDiscoveredSqlAliasException: Encountered a duplicated sql alias
- getpwuid()
- 如何生成uimage
- Result Maps collection already contains value for
- 'setting build path' has encountered
- iOS开发从入门到精通--UIViewController使用
- DRUID连接池的实用 配置详解
- 超级精简版/超精简/懂你版IDM 6.25 build 23推荐
- CodeForces 175D Plane of Tanks: Duel (概率)
- UILabel,文字添加下划线,中划线
- 关于UINavigationBar加载不规则的图片的总结
- Css3 Media Query实现响应式的方法总结
- [leetcode-375]Guess Number Higher or Lower II(java)
- ueditor使用
- LeetCode 232. Implement Queue using Stacks
- UGUI工厂
- Qt Quick<OpacityMask> 圆角图片、异形图片的合成
- iOS开发 UITextFild/TextView限制字数(含联想词汇)
- LeetCode 347. Top K Frequent Elements