Phương thức Clear() đặt Length = 0, giải phóng nội dung nhưng giữ dung lượng (Capacity) để tái sử dụng.
Ví dụ
using System;
using System.Text;
public class Demo
{
public static void Main()
{
string[] myStr = { "One", "Two", "Three", "Four" };
StringBuilder str = new StringBuilder("We will print now...").AppendLine();
foreach (string item in myStr)
str.Append(item).AppendLine();
Console.WriteLine(str.ToString());
int len = str.Length;
Console.WriteLine("Độ dài: " + len);
str.Clear();
int len2 = str.Length;
Console.WriteLine("Độ dài sau Clear: " + len2);
Console.ReadLine();
}
}
Kết quả
We will print now... One Two Three Four Độ dài: 40 Độ dài sau Clear: 0