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

เข้าถึงตัวอักษรใน C# StringBuilder


ภาพรวม

ใช้ indexer [] ของ StringBuilder เพื่อ อ่านตัวอักษร ที่ตำแหน่งที่ระบุ (read-only access)

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

using System;
using System.Text;

public class Demo
{
    public static void Main()
    {
        StringBuilder str = new StringBuilder();
        str.Append("premium");
        Console.WriteLine("String : " + str);
        Console.Write("Accessing 5th character : ");
        Console.WriteLine(str[4]); // index 4 = ตัวที่ 5
    }
}

ผลลัพธ์

String : premium
Accessing 5th character : i

คำอธิบายดัชนี

"premium" = [0]p [1]r [2]e [3]m [4]i [5]u [6]m

index 4 = 'i' (ตัวที่ 5)

ข้อสังเกต

  • Indexer คืนค่า char (read-only property getter)
  • Setter แยกต่างหาก: sb[index] = 'x'; (เห็นในบทความก่อนหน้า)
  • โยน ArgumentOutOfRangeException หาก index < 0 หรือ >= Length
  • ไม่มีเมธอด CharAt() เช่น Java - ใช้ indexer แทน