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

เมธอด String.Insert() ใน C# : แทรกสตริงที่ตำแหน่งที่กำหนด

เมธอด String.Insert() ใน C# ใช้สร้างสตริงใหม่โดยการแทรกสตริงที่ระบุเข้าไปที่ตำแหน่งดัชนี (index) ที่กำหนดของสตริงต้นฉบับ เนื่องจาก string เป็น immutable เมธอดนี้จึงคืนค่าสตริงใหม่ ไม่ได้แก้ไขสตริงเดิม

รูปแบบไวยากรณ์ (Syntax)

public string Insert(int startIndex, string value);
  • startIndex : ดัชนีเริ่มต้นที่จะแทรก (zero-based) ต้องอยู่ระหว่าง 0 ถึง Length
  • value : สตริงที่ต้องการแทรก
  • คืนค่า : สตริงใหม่ที่มีการแทรกแล้ว

ตัวอย่างที่ 1: แทรกช่องว่างระหว่างชื่อ-นามสกุล

using System;

public class Demo
{
    public static void Main()
    {
        String str = "JohnWick";
        
        Console.WriteLine("Initial string = " + str);
        
        // แทรกช่องว่างที่ index 5 (หลัง "John")
        String res = str.Insert(5, " ");
        
        Console.WriteLine("Updated = " + res);
    }
}

ผลลัพธ์

Initial string = JohnWick
Updated = John Wick

ตัวอย่างที่ 2: แทรกวลีในประโยค

using System;

public class Demo
{
    public static void Main()
    {
        String str = "WelcomeJacob";
        
        Console.WriteLine("Initial string = " + str);
        
        // แทรก " here, " ที่ index 7 (หลัง "Welcome")
        String res = str.Insert(7, " here, ");
        
        Console.WriteLine("Updated = " + res);
    }
}

ผลลัพธ์

Initial string = WelcomeJacob
Updated = Welcome here, Jacob

ข้อผิดพลาดที่พบบ่อย

ArgumentOutOfRangeException จะเกิดขึ้นหาก:
• startIndex < 0
• startIndex > str.Length
• value เป็น null

สรุป

  • Insert() สร้างสตริงใหม่ ไม่แก้ไขสตริงเดิม (immutable)
  • index 0 = หน้าสตริง, index Length = ท้ายสตริง (ต่อท้าย)
  • สำหรับการแทรกหลายครั้งหรือในลูป ให้ใช้ StringBuilder.Insert() แทนเพื่อประสิทธิภาพ
  • เวลาสำหรับการ Insert คือ O(n) โดย n = ความยาวสตริง