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

Append StringBuilder ใน C# พร้อมขึ้นบรรทัดใหม่ (AppendLine)


ภาพรวม

เมธอด AppendLine() ของ StringBuilder เพิ่มข้อความ พร้อมขึ้นบรรทัดใหม่ (append newline) โดยอัตโนมัติ

รูปแบบการใช้งาน

StringBuilder sb = new StringBuilder();
sb.AppendLine("Accessories");
sb.AppendLine();        // บรรทัดว่าง
sb.AppendLine("Electronics");

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

using System;
using System.Text;

class Demo
{
    static void Main()
    {
        StringBuilder str = new StringBuilder();
        str.AppendLine("Accessories");
        str.AppendLine();
        str.AppendLine("Electronics");
        Console.Write(str);
    }
}

ผลลัพธ์

Accessories

Electronics

ข้อสังเกต

  • AppendLine() ใช้ Environment.NewLine (Windows: \r\n, Linux/macOS: \n)
  • AppendLine(string) = Append(string + Environment.NewLine)
  • เหมาะสำหรับสร้างไฟล์ข้อความ, log, report แบบหลายบรรทัด