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

ล้าง StringBuilder ใน C #


หากต้องการล้าง StringBuilder ให้ใช้วิธีการ Clear()

สมมติว่าเราได้ตั้งค่า StringBuilder ต่อไปนี้ -

string[] myStr = { "One", "Two", "Three", "Four" };
StringBuilder str = new StringBuilder("We will print now...").AppendLine();

ตอนนี้ ใช้วิธี Clear() เพื่อล้าง StringBuilder -

str.Clear();

ให้เราดูรหัสที่สมบูรณ์ -

ตัวอย่าง

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();
   }
}

ผลลัพธ์

We will print now...
One
Two
Three
Four

Length: 40
Length after using Clear: 0