您的位置:首页 > 产品设计 > UI/UE

system.string 和System.Text.StringBuilder的不同

2011-06-27 13:46 399 查看
1. string类

字符串是 Unicode 字符的有序集合,用于表示文本。String 对象是 System .

Char 对象的有序集合,用于表示字符串。 String 对

象的值是该有序集合的内容,并且该值是不可变的。

2.StringBuilder

表示可变字符字符串。此类不能被继承。此类表示值为可变字符序列的类似字符串的对象。

之所以说值是可变的,是因为在通过追加、移除、替换或插入字符而创建它后可以对它进行修改

using System;
using System.Text;

public sealed class App
{
static void Main()
{
// Create a StringBuilder that expects to hold 50 characters.
// Initialize the StringBuilder with "ABC".
StringBuilder sb = new StringBuilder("ABC", 50);

// Append three characters (D, E, and F) to the end of the StringBuilder.
sb.Append(new char[] { 'D', 'E', 'F' });

// Append a format string to the end of the StringBuilder.
sb.AppendFormat("GHI{0}{1}", 'J', 'k');

// Display the number of characters in the StringBuilder and its string.
Console.WriteLine("{0} chars: {1}", sb.Length, sb.ToString());

// Insert a string at the beginning of the StringBuilder.
sb.Insert(0, "Alphabet: ");

// Replace all lowercase k's with uppercase K's.
sb.Replace('k', 'K');

// Display the number of characters in the StringBuilder and its string.
Console.WriteLine("{0} chars: {1}", sb.Length, sb.ToString());
}
}

// This code produces the following output.
//
// 11 chars: ABCDEFGHIJk
// 21 chars: Alphabet: ABCDEFGHIJK


String 对象是不可改变的。每次使用 System.String 类中的方法之一时,都要在内存中创建一个新的字符串对象,

这就需要为该新对象分配新的空间。在需要对字符串执行重复修改的情况下,与创建新的 String 对象相关的系统开销可能会非常昂贵。

如果要修改字符串而不创建新的对象,则可以使用 System.Text.StringBuilder 类。

例如,当在一个循环中将许多字符串连接在一起时,使用 StringBuilder 类可以提升性能。

下表列出了可以用来修改 StringBuilder 的内容的方法。

StringBuilder.Append 将信息追加到当前 StringBuilder 的结尾。
StringBuilder.AppendFormat 用带格式文本替换字符串中传递的格式说明符。
StringBuilder.Insert 将字符串或对象插入到当前 StringBuilder 对象的指定索引处。
StringBuilder.Remove 从当前 StringBuilder 对象中移除指定数量的字符。
StringBuilder.Replace 替换指定索引处的指定字符。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: