Để xóa một StringBuilder, hãy sử dụng phương thức Clear ().
Giả sử chúng tôi đã đặt StringBuilder sau -
string[] myStr = { "One", "Two", "Three", "Four" };
StringBuilder str = new StringBuilder("We will print now...").AppendLine(); Bây giờ, sử dụng phương thức Clear () để xóa StringBuilder -
str.Clear();
Hãy cho chúng tôi xem mã hoàn chỉnh -
Ví dụ
using System;
using System.Text;
public class Demo {
public static void Main() {
// string array
string[] myStr = { "One", "Two", "Three", "Four" };
StringBuilder str = new StringBuilder("We will print now...").AppendLine();
// foreach loop to append elements
foreach (string item in myStr) {
str.Append(item).AppendLine();
}
Console.WriteLine(str.ToString());
int len = str.Length;
Console.WriteLine("Length: "+len);
// clearing
str.Clear();
int len2 = str.Length;
Console.WriteLine("Length after using Clear: "+len2);
Console.ReadLine();
}
} Đầu ra
We will print now... One Two Three Four Length: 40 Length after using Clear: 0