StringBuilder 类

命名空间:System.Text

程序集:mscorlib(在 mscorlib.dll 中)

     此类表示值为可变字符序列的类似字符串的对象。之所以说值是可变的,是因为在通过追加、移除、替换或插入字符而创建它后可以对它进行修改。。

     大多数修改此类的实例的方法都返回对同一实例的引用。由于返回的是对实例的引用,因此可以调用该引用的方法或属性。如果想要编写将连续操作依次连接起来的单个语句,这将很方便。。

    StringBuilder 的容量是实例在任何给定时间可存储的最大字符数,并且大于或等于实例值的字符串表示形式的长度。容量可通过 Capacity 属性或 EnsureCapacity 方法来增加或减少,但它不能小于 Length 属性的值。。

    

性能注意事项:

     Concat 和 AppendFormat 方法都将新数据串连到一个现有的 String 或 StringBuilder 对象。String 对象串联操作总是用现有字符串和新数据创建新的对象。StringBuilder对象维护一个缓冲区,以便容纳新数据的串联。如果有足够的空间,新数据将被追加到缓冲区的末尾;否则,将分配一个新的、更大的缓冲区,原始缓冲区中的数据被复制到新的缓冲区,然后将新数据追加到新的缓冲区。。

    给实现者的说明 此实现的默认容量是 16,默认的最大容量是 Int32.MaxValue。 当实例值增大时,StringBuilder 可按存储字符的需要分配更多的内存,同时对容量进行相应的调整。分配的内存量是特定于实现的,而且如果所需内存量大于最大容量,会引发 ArgumentOutOfRangeException。 例如,Append、AppendFormat、EnsureCapacity、Insert 和 Replace方法能增大实例的值。 通过 Chars 属性可以访问 StringBuilder 的值中的单个字符。索引位置从零开始。。

 

using namespace System;
using namespace System::Text;

int main()
{
    // Create a StringBuilder that expects to hold 50 characters.
    // Initialize the StringBuilder with "ABC".
    StringBuilder^ sb = gcnew StringBuilder("ABC", 50);

    // Append three characters (D, E, and F) to the end of the
    // StringBuilder.
    sb->Append(gcnew array<Char>{'D', 'E', 'F'});

    // Append a format string to the end of the StringBuilder.
    sb->AppendFormat("GHI{0}{1}", (Char)'J', (Char)'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

   

原文地址:https://www.cnblogs.com/Suk1M/p/4529117.html