StringBuilder用法

//来自MSDN,不太懂英文可以使用百度翻译。

//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());
// Console.ReadKey();
// }
//} // This code produces the following output.
//
// 11 chars: ABCDEFGHIJk //计算字符个数是从1开始计数,而不是从0.
// 21 chars: Alphabet: ABCDEFGHIJK //备注 //SubString类表示值为可变字符序列的类似字符串的对象。之所以说值是可变的,是因为在通过追加、移除、替换或插入字符而创建它后可以对它进行修改。 //大多数修改此类的实例的方法都返回对同一实例的引用。由于返回的是对实例的引用,因此可以调用该引用的方法或属性。如果想要编写将连续操作依次连接起来的单个语句,这将很方便。 //StringBuilder 的容量是实例在任何给定时间可存储的最大字符数,并且大于或等于实例值的字符串表示形式的长度。容量可通过 Capacity 属性或 EnsureCapacity 方法来增加或减少,但它不能小于 Length 属性的值。 //如果在初始化 StringBuilder 的实例时没有指定容量或最大容量,则使用特定于实现的默认值。 //性能注意事项 //Concat 和 AppendFormat 方法都将新数据串连到一个现有的 String 或 StringBuilder 对象。String 对象串联操作总是用现有字符串和新数据创建新的对象。StringBuilder 对象维护一个缓冲区,以便容纳新数据的串联。如果有足够的空间,新数据将被追加到缓冲区的末尾;否则,将分配一个新的、更大的缓冲区,原始缓冲区中的数据被复制到新的缓冲区,然后将新数据追加到新的缓冲区。 //String 或 StringBuilder 对象的串联操作的性能取决于内存分配的发生频率。String 串联操作每次都分配内存,而 StringBuilder 串联操作仅当 StringBuilder 对象缓冲区太小而无法容纳新数据时才分配内存。因此,如果串联固定数量的 String 对象,则 String 类更适合串联操作。这种情况下,编译器甚至会将各个串联操作组合到一个操作中。如果串联任意数量的字符串,则 StringBuilder 对象更适合串联操作;例如,某个循环对用户输入的任意数量的字符串进行串联。 //给实现者的说明 此实现的默认容量是 16,默认的最大容量是 Int32.MaxValue。 当实例值增大时,StringBuilder 可按存储字符的需要分配更多的内存,同时对容量进行相应的调整。分配的内存量是特定于实现的,而且如果所需内存量大于最大容量,会引发 ArgumentOutOfRangeException。 例如,Append、AppendFormat、EnsureCapacity、Insert 和 Replace 方法能增大实例的值。 通过 Chars 属性可以访问 StringBuilder 的值中的单个字符。索引位置从零开始。
上一篇:Ubuntu图形界面和字符界面转换、指定默认启动界面


下一篇:时间序列分解算法:STL