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

วนลูป StringBuilder ใน C# ด้วย foreach


ภาพรวม

StringBuilder ไม่ implement IEnumerable<char> จึง ไม่สามารถ foreach ได้โดยตรง แต่สามารถวนลูปผ่าน ToString() หรือ indexer

ตัวอย่าง: ใช้ foreach กับอาร์เรย์สตริง แล้ว Append เข้า StringBuilder

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

ผลลัพธ์

We will print now...
One
Two
Three
Four

วิธีวนลูป StringBuilder เอง

  • for (int i = 0; i < sb.Length; i++) char c = sb[i];
  • foreach (char c in sb.ToString()) - สร้างสตริงชั่วคราว
  • foreach (char c in sb.ChunkEnumerable) - .NET 6+ (internal)