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

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
替换指定索引处的指定字符。

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值