Giới thiệu
Phương thức StringBuilder.Remove(int startIndex, int length) xóa length ký tự bắt đầu từ startIndex (0-based). Trả về chính instance StringBuilder (fluent).
Ví dụ cơ bản
StringBuilder myStr = new StringBuilder("Framework");
myStr.Remove(5, 4); // Xóa 4 ký tự từ index 5: "work" -> "Frame"
Ví dụ hoàn chỉnh
using System;
using System.Text;
public class Program
{
public static void Main()
{
StringBuilder myStr = new StringBuilder("Framework");
Console.WriteLine("Initial String: " + myStr);
myStr.Remove(5, 4);
Console.WriteLine("New string: " + myStr);
}
}
Kết quả
Initial String: Framework New string: Frame
Giải thích index
Chuỗi "Framework" (index 0-based):
F r a m e w o r k 0 1 2 3 4 5 6 7 8
Remove(5, 4): Bắt đầu index 5 ('w'), xóa 4 ký tự: 'w','o','r','k' -> còn "Frame".
Các phương thức chỉnh sửa StringBuilder khác
| Phương thức | Mô tả |
|---|---|
Insert(index, value) | Chèn chuỗi tại index |
Remove(index, length) | Xóa length ký tự từ index |
Replace(old, new) | Thay thế tất cả old bằng new |
Clear() | Xóa toàn bộ nội dung |
Append(value) | Thêm vào cuối |
Lưu ý
- Ném
ArgumentOutOfRangeExceptionnếu index < 0, index > Length, hoặc index+length > Length. - StringBuilder mutable - thay đổi in-place, không tạo object mới.
- Hiệu quả cho thao tác chuỗi nhiều lần (so với string immutable).