StringBuilder.Capacity属性用于获取或设置当前实例分配的内存中可以包含的最大字符数。
语法:public int Capacity {get; set; }【如何在C#中查找StringBuilder的容量(示例)】下面的程序将说明上述属性的用法:
返回值:该属性将返回当前实例分配的内存中可以包含的最大字符数。其值的范围可以从” 长度” 到” 最大容量” 。
异常:如果为set操作指定的值小于此实例的当前长度, 或者为set操作指定的值大于最大容量, 则此属性将提供ArgumentOutOfRangeException。
示例1:
//C# program to demonstrate
//the Capacity() Property
using System;
using System.Text;
class GFG {//Main Method
public static void Main(String[] args)
{//create a StringBuilder object, //default capacity will be 16
StringBuilder str = new StringBuilder();
//get default capacity
int cap = str.Capacity;
Console.WriteLine( "Deafult Capacity of StringBuilder = "
+ cap);
//add the String to StringBuilder Object
str.Append( "Geek" );
//get capacity
cap = str.Capacity;
//print the result
Console.WriteLine( "StringBuilder = " + str);
Console.WriteLine( "Current Capacity of StringBuilder = "
+ cap);
}
}
输出如下:
Deafult Capacity of StringBuilder = 16
StringBuilder = Geek
Current Capacity of StringBuilder = 16
示例2:
//C# program to demonstrate
//the Capacity() Property
using System;
using System.Text;
class GFG {
public static void Main(String[] args)
{//create a StringBuilder object
//with a String passed as parameter
StringBuilder str =
new StringBuilder( "WelcomeGeeks" );
//get capacity
int capacity = str.Capacity;
//print the result
Console.WriteLine( "StringBuilder = " + str);
Console.WriteLine( "Capacity of StringBuilder = "
+ capacity);
}
}
输出如下:
StringBuilder = WelcomeGeeks
Capacity of StringBuilder = 16
参考:
- https://docs.microsoft.com/en-us/dotnet/api/system.text.stringbuilder.capacity?view=netframework-4.7.2
推荐阅读
- 如何在Golang中找到指针的容量()
- 如何在不使用sizeof的情况下在C/C++中查找数组的大小()
- 如何使用计算反正切arc(实现示例)
- 如何在cmd(命令行)上执行C#程序()
- 如何有效地对20年代的大列表日期进行排序
- Python如何使用Pandas实现vLookup(代码实例)
- 如何使用PHP将HTML标签显示为纯文本
- 编译mate-control-center(error: required directory ./help does not exist)
- 生产制造业如何谋求数字化转型(需要哪些信息化系统做支撑?)