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

Thay thế ký tự đặc biệt trong chuỗi C#

Tương tự bài trước, dùng Replace để thay ký tự đặc biệt ($, @, #, v.v.) bằng ký tự khác.

Ví dụ minh họa

using System;

class Program
{
    static void Main()
    {
        string str = "abcd$ef$gh";
        Console.WriteLine($"Chuỗi gốc: {str}");
        
        // Thay '$' bằng 'k'
        string result = str.Replace('$', 'k');
        Console.WriteLine($"Sau thay thế: {result}");
        
        // Thay thế nhiều ký tự đặc biệt cùng lúc
        string messy = "user@domain.com#123$test";
        string clean = messy
            .Replace("@", "[at]")
            .Replace("#", "[hash]")
            .Replace("$", "[dollar]");
        Console.WriteLine($"\nGốc: {messy}");
        Console.WriteLine($"Sạch: {clean}");
        
        // Dùng Regex cho pattern phức tạp
        System.Text.RegularExpressions.Regex regex = new System.Text.RegularExpressions.Regex(@"[^\w\s]");
        string onlyAlphaNum = regex.Replace(messy, "");
        Console.WriteLine($"Chỉ alphanumeric: {onlyAlphaNum}");
    }
}

Kết quả đầu ra

Chuỗi gốc: abcd$ef$gh
Sau thay thế: abcdkefkgh

Gốc: user@domain.com#123$test
Sạch: user[at]domain.com[hash]123[dollar]test
Chỉ alphanumeric: userdomaincom123test

Mẹo: Chuỗi nhiều Replace tạo ra nhiều object trung gian. Dùng StringBuilder hoặc Regex.Replace cho hiệu năng tốt hơn.