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

แทนที่ตัวอักษรใน String ด้วย Replace ใน C#

ภาพรวม

ใช้เมธอด String.Replace แทนที่ตัวอักษรหรือสตริงย่อยทั้งหมดในสตริง คืนค่าสตริงใหม่ (String เป็น immutable)

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


using System;

public class Program {
    public static void Main() {
        string str = "dem* text";
        Console.WriteLine($"Original: '{str}'");

        // แทนที่ '*' ด้วย 'o'
        string result = str.Replace('*', 'o');
        Console.WriteLine($"After replace: '{result}'");

        // แทนที่สตริงย่อย
        string str2 = "Hello World";
        string result2 = str2.Replace("World", "C#");
        Console.WriteLine($"Replace substring: '{result2}'");

        // แทนที่หลายครั้ง (Chaining)
        string str3 = "a-b-c-d";
        string result3 = str3.Replace("-", "").Replace("c", "X");
        Console.WriteLine($"Chained: '{result3}'"); // abXd
    }
}

ผลลัพธ์


Original: 'dem* text'
After replace: 'demo text'
Replace substring: 'Hello C#'
Chained: 'abXd'

Overloads ของ Replace

Signatureคำอธิบาย
Replace(char oldChar, char newChar)แทนที่ตัวอักษรเดี่ยว
Replace(string oldValue, string newValue)แทนที่สตริงย่อย
Replace(string oldValue, string newValue, StringComparison)แทนที่พร้อมระบุการเปรียบเทียบ (C# 10+)
Replace(char oldChar, char newChar, StringComparison)แทนที่ char พร้อม StringComparison (C# 10+)

Case-Insensitive Replace (ก่อน C# 10)


using System.Text.RegularExpressions;

string str = "Hello WORLD";
string result = Regex.Replace(str, "world", "C#", RegexOptions.IgnoreCase);
Console.WriteLine(result); // Hello C#

StringBuilder สำหรับ Performance


using System.Text;

StringBuilder sb = new StringBuilder("a-b-c-d-e-f-g");
sb.Replace("-", ""); // แก้ไขในที่เดียว (mutable)
Console.WriteLine(sb.ToString()); // abcdefg

ข้อควรระวัง

  • String เป็น immutable - Replace คืนค่าสตริงใหม่ ต้อง assign ไว้
  • str.Replace("a", "b"); โดยไม่ assign = ไม่มีผลอะไรเกิดขึ้น
  • แทนที่ทั้งหมด (All occurrences) ไม่ใช่แค่ครั้งแรก
  • ใช้ Regex.Replace สำหรับ pattern matching หรือ case-insensitive