C#中的StringBuilder.EnsureCapacity()方法
本文向大家介绍C#中的StringBuilder.EnsureCapacity()方法,包括了C#中的StringBuilder.EnsureCapacity()方法的使用技巧和注意事项,需要的朋友参考一下
C#中的StringBuilder.EnsureCapacity()方法用于确保StringBuilder实例的容量至少为指定值。
语法
语法如下-
public int EnsureCapacity (int capacity);
以上,参数容量是要确保的最小容量。
示例
现在让我们看一个例子-
using System; using System.Text; public class Demo{ public static void Main(){ StringBuilder strBuilder = new StringBuilder("jhbjhb"); Console.WriteLine("String = "+strBuilder); Console.WriteLine("StringBuilder capacity= "+strBuilder.Capacity); strBuilder.EnsureCapacity(20); Console.WriteLine("StringBuilder capacity= "+strBuilder.Capacity); char[] arr = new char[5] {'a', 'b', 'c', 'd', 'e'}; strBuilder.CopyTo(1, arr, 1, 3); Console.WriteLine("\nCopied String in char array..."); Console.WriteLine(arr); } }
输出结果
这将产生以下输出-
String = jhbjhb StringBuilder capacity= 16 StringBuilder capacity= 20 Copied String in char array... ahbje
示例
现在让我们来看另一个示例-
using System; using System.Text; public class Demo{ public static void Main(){ StringBuilder strBuilder = new StringBuilder("Katie"); Console.WriteLine("String = "+strBuilder); 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