String,众所周知,静态的.不可改变,也就是说 immutable. 要想变,也成,瞒天过海,有开销.因此StringBuilder Class的出现,可以动态地修改String, 下面介绍 StringBuilder Constructor :
- StringBuilder() Initializes a new default instance with a size of 16
- StringBuilder(int) Initializes a new instance with a capacity of int
- StringBuilder(int1, int2) Initializes a new instance with a default capacity of int1 and a maximum capacity of int2
- StringBuilder(string) Initializes a new instance with a default value of string
- StringBuilder(string, int) Initializes a new instance with a default value of string and a capacity of int
- StringBuilder(string, int1, int2, int3) Initializes a new instance with a default value starting at position int1 of string, int2 characters long, with a capacity of int3
SampleBuilder.cs 程序
using System;using System.Text;class SampleBuilder{ public static void Main () { StringBuilder sb = new StringBuilder("test string"); int length = 0; length = sb.Length; Console.WriteLine("The result is: '{0}'", sb); Console.WriteLine("The length is: {0}", length); sb.Length = 4; length = sb.Length; Console.WriteLine("The result is: '{0}'", sb); Console.WriteLine("The length is: {0}", length); sb.Length = 20; length = sb.Length; Console.WriteLine("The result is: '{0}'", sb); Console.WriteLine("The length is: {0}", length); }}
输出结果:
C:/>SampleBuilderThe result is: 'test string'The length is: 11The result is: 'test'The length is: 4The result is: 'test 'The length is: 20