ภาพรวม
StringBuilder รองรับ indexer ([]) สำหรับ อ่าน/เขียนตัวอักษร ที่ตำแหน่งเฉพาะ (mutable string)
รูปแบบการใช้งาน
StringBuilder sb = new StringBuilder("pre");
sb[2] = 'o'; // เปลี่ยน index 2 ('r' -> 'o') → "pro"
ตัวอย่างโค้ดเต็ม
using System;
using System.Text;
public class Demo
{
public static void Main()
{
StringBuilder str = new StringBuilder();
str.Append("pre");
Console.WriteLine("String : " + str);
str[2] = 'o';
Console.WriteLine("Change 3rd character");
Console.WriteLine("New String : " + str);
}
}
ผลลัพธ์
String : pre Change 3rd character New String : pro
ข้อดีของ StringBuilder
- Mutable - แก้ไขได้โดยไม่สร้าง object ใหม่ (ต่างจาก string ที่ immutable)
- O(1) สำหรับการเข้าถึง/แก้ไข index
- เหมาะสำหรับ string manipulation ซ้ำๆ (loop, concatenation มาก)
- Capacity จัดการอัตโนมัติ (ค่าเริ่มต้น 16, คูณ 2 เมื่อเต็ม)