C#中的StringBuilder.ToString()方法用于将StringBuilder的值转换为String。
语法如下-
public override string ToString (); public string ToString (int begnIndex, int len);
上面的参数begnIndex在这种情况下是子字符串的开始位置,而len是子字符串的长度。
现在让我们看一个例子-
using System; using System.Text; public class Demo{ public static void Main(){ StringBuilder strBuilder = new StringBuilder("Katie"); Console.WriteLine("String = "+strBuilder.ToString()); Console.WriteLine("\nStringBuilder capacity = "+strBuilder.Capacity); Console.WriteLine("StringBuilder length = "+strBuilder.Length); strBuilder.EnsureCapacity(35); Console.WriteLine("\nStringBuilder capacity= "+strBuilder.Capacity); Console.WriteLine("StringBuilder length = "+strBuilder.Length); strBuilder.EnsureCapacity(0); strBuilder.Length = 0; Console.WriteLine("\nStringBuilder capacity= "+strBuilder.Capacity); Console.WriteLine("StringBuilder length = "+strBuilder.Length); } }
输出结果
这将产生以下输出-
String = Katie StringBuilder capacity = 16 StringBuilder length = 5 StringBuilder capacity= 35 StringBuilder length = 5 StringBuilder capacity= 35 StringBuilder length = 0
现在让我们来看另一个示例-
using System; using System.Text; public class Demo{ public static void Main(){ StringBuilder strBuilder = new StringBuilder("TomHanks"); Console.WriteLine("StringBuilder = "+strBuilder.ToString()); Console.WriteLine("String = "+strBuilder.ToString(3, 5)); Console.WriteLine("\nStringBuilder capacity = "+strBuilder.Capacity); Console.WriteLine("StringBuilder length = "+strBuilder.Length); strBuilder.EnsureCapacity(35); Console.WriteLine("\nStringBuilder capacity= "+strBuilder.Capacity); Console.WriteLine("StringBuilder length = "+strBuilder.Length); strBuilder.EnsureCapacity(0); strBuilder.Length = 0; Console.WriteLine("\nStringBuilder capacity= "+strBuilder.Capacity); Console.WriteLine("StringBuilder length = "+strBuilder.Length); } }
输出结果
这将产生以下输出-
StringBuilder = TomHanks String = Hanks StringBuilder capacity = 16 StringBuilder length = 8 StringBuilder capacity= 35 StringBuilder length = 8 StringBuilder capacity= 35 StringBuilder length = 0