เนื่องจากสตริงใน C# เป็น Immutable จึงไม่สามารถแก้ไขตัวอักษรโดยตรงได้ วิธีแก้คือแปลงเป็นอาร์เรย์ตัวอักษร (char[]) แก้ไข แล้วสร้างสตริงใหม่
ขั้นตอน
- แปลงสตริงเป็น
char[]ด้วยToCharArray() - แก้ไขค่าที่ดัชนีที่ต้องการ
- สร้างสตริงใหม่ด้วย Constructor
new string(charArray)
ตัวอย่าง: แทนที่ตัวอักษรแรก (Index 0)
using System;
using System.Collections.Generic;
public class Demo
{
public static void Main(string[] args)
{
string str1 = "Port";
Console.WriteLine("สตริงต้นฉบับ: " + str1);
char[] ch = str1.ToCharArray();
ch[0] = 'F'; // แทนที่ Index 0
string str2 = new string(ch);
Console.WriteLine("สตริงใหม่: " + str2);
}
}
ผลลัพธ์
สตริงต้นฉบับ: Port สตริงใหม่: Fort
วิธีการอื่นๆ
- StringBuilder: ใช้
sb[index] = 'F';แล้วsb.ToString() - Substring + Concatenation:
str.Substring(0, index) + newChar + str.Substring(index + 1) - LINQ:
new string(str.Select((c, i) => i == index ? newChar : c).ToArray())
ประสิทธิภาพ: StringBuilder เร็วที่สุดสำหรับการแก้ไขหลายครั้ง char[] เร็วและเรียบง่ายสำหรับการแก้ไขครั้งเดียว