StringBuilder cho phép truy xuất và gán ký tự qua indexer (0-based). Ví dụ thay ký tự tại vị trí 2 (thứ 3).
Ví dụ
using System;
using System.Text;
public class Demo
{
public static void Main()
{
StringBuilder str = new StringBuilder();
str.Append("pre");
Console.WriteLine("Chuỗi: " + str);
Console.WriteLine("Thay ký tự thứ 3");
str[2] = 'o';
Console.WriteLine("Chuỗi mới: " + str);
}
}
Kết quả
Chuỗi: pre Thay ký tự thứ 3 Chuỗi mới: pro
Lưu ý: Indexer chỉ cho phép gán ký tự đơn (char), không gán chuỗi. Dùng Replace để thay chuỗi con.