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

โปรแกรม C# ลบตัวอักษรเริ่มจากดัชนีที่กำหนดใน StringBuilder


ภาพรวม

เมธอด Remove(int startIndex, int length) ลบตัวอักษร length ตัว เริ่มจาก startIndex

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

using System;
using System.Text;

public class Program
{
    public static void Main()
    {
        StringBuilder str = new StringBuilder("Airport");
        Console.WriteLine("String: " + str);
        str.Remove(3, 4); // ลบ 4 ตัว ตั้งแต่ index 3 ("port")
        Console.WriteLine("String after removing characters: " + str);
    }
}

ผลลัพธ์

String: Airport
String after removing characters: Air

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

"Airport" = [0]A [1]i [2]r [3]p [4]o [5]r [6]t

Remove(3, 4) ลบ index 3,4,5,6 ("port") เหลือ "Air"

เมธอดแก้ไข StringBuilder อื่นๆ

เมธอดคำอธิบาย
Insert(index, string)แทรกสตริงที่ดัชนี
Replace(old, new)แทนที่ substring ทุกที่ที่พบ
Append(string)ต่อท้าย
Clear()ล้างทั้งหมด