Computer >> Hướng Dẫn Máy Tính >  >> Lập Trình >> C#

Thay thế từ trong chuỗi C#

Thay thế từ/substring: string.Replace(old, new) - trả về chuỗi mới (string immutable).

Ví dụ minh họa

using System;

class Program
{
    static void Main()
    {
        string str = "Demo text!";
        
        Console.WriteLine($"Gốc: {str}");
        
        // Thay "Demo " → "New "
        string result = str.Replace("Demo ", "New ");
        Console.WriteLine($"Sau Replace: {result}");
        
        // Thay nhiều lần
        string template = "Hello {name}, welcome to {place}!";
        string personalized = template
            .Replace("{name}", "An")
            .Replace("{place}", "Hanoi");
        Console.WriteLine($"\nTemplate: {template}");
        Console.WriteLine($"Personalized: {personalized}");
        
        // Thay ký tự đơn
        string chars = "a-b-c-d";
        Console.WriteLine($"\nGốc: {chars}");
        Console.WriteLine($"Thay '-' bằng ' ': {chars.Replace('-', ' ')}");
        
        // Chuỗi gốc KHÔNG thay đổi (immutable)
        Console.WriteLine($"\nChuỗi gốc vẫn: {str}");
    }
}

Kết quả đầu ra

Gốc: Demo text!
Sau Replace: New text!

Template: Hello {name}, welcome to {place}!
Personalized: Hello An, welcome to Hanoi!

Gốc: a-b-c-d
Thay '-' bằng ' ': a b c d

Chuỗi gốc vẫn: Demo text!

Lưu ý: Replace thay thế tất cả occurrences. Muốn thay 1 lần → dùng Regex.Replace(input, pattern, replacement, 1) hoặc logic thủ công với IndexOf + Remove + Insert.