ขั้นแรก ตั้งค่าอาร์เรย์สตริงและ StringBuilder -
// string array
string[] myStr = { "One", "Two", "Three", "Four" };
StringBuilder str = new StringBuilder("We will print now...").AppendLine(); ตอนนี้ ใช้ foreach loop เพื่อวนซ้ำ -
foreach (string item in myStr) {
str.Append(item).AppendLine();
} ต่อไปนี้เป็นรหัสที่สมบูรณ์ -
ตัวอย่าง
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());
Console.ReadLine();
}
} ผลลัพธ์
We will print now... One Two Three Four