Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> C#

ล้าง StringBuilder ใน C# (Clear)


ภาพรวม

เมธอด Clear() ของ StringBuilder ใช้ ล้างเนื้อหาทั้งหมด ทำให้ Length = 0 แต่ Capacity คงเดิม

ตัวอย่างโค้ดเต็ม

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());
        Console.WriteLine("Length: " + str.Length); // 40
        str.Clear();
        Console.WriteLine("Length after using Clear: " + str.Length); // 0
    }
}

ผลลัพธ์

We will print now...
One
Two
Three
Four
Length: 40
Length after using Clear: 0

ข้อสังเกต

  • Clear() ไม่ปล่อยหน่วยความจำ (Capacity คงเดิม) - ใช้ sb.Capacity = 0; หากต้องการปล่อย
  • หลัง Clear() สามารถใช้ StringBuilder เดียวกันต่อได้ (reuse) - ประหยัด allocation
  • เทียบเท่า: sb.Length = 0; (property setter)