StringBuilder.Clear方法用于从当前StringBuilder实例中删除所有字符。
句法:
public System.Text.StringBuilder Clear ();
它返回一个StringBuilder对象,其长度将为零。
笔记:
- 清除是一种便捷方法,等效于将当前实例的Length属性设置为0(零)。
- 调用Clear方法不会修改当前实例的Capacity或MaxCapacity属性。
例子:
// C# program to demonstrate
// the Clear() Method
using System;
using System.Text;
class GFG {
// Main Method
public static void Main(String[] args)
{
// Creating a StringBuilder object
StringBuilder sb1 = new StringBuilder("GeeksforGeeks");
// printing the length of "GeeksforGeeks"
Console.WriteLine("The String is: {0} \nTotal characters -- {1}",
sb1.ToString(), sb1.Length);
// using the method
sb1.Clear();
// printing the length of "GeeksforGeeks"
Console.WriteLine("The String is: {0} \nTotal characters -- {1}",
sb1.ToString(), sb1.Length);
sb1.Append("This is C# Tutorials.");
// printing the length of "GeeksforGeeks"
Console.WriteLine("The String is: {0} \nTotal characters -- {1}",
sb1.ToString(), sb1.Length);
}
}
输出:
The String is: GeeksforGeeks
Total characters -- 13
The String is:
Total characters -- 0
The String is: This is C# Tutorials.
Total characters -- 22
参考:
- https://docs.microsoft.com/zh-cn/dotnet/api/system.text.stringbuilder.clear?view=netframework-4.7.2