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:/> SampleBuilder The result is: 'test string'The length is: 11The result is: 'test'The length is: 4The result is: 'test 'The length is: 20