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

Thay thế chuỗi không phân biệt chữ hoa/thường (Case-Insensitive Replace) trong C#

string.Replace phân biệt chữ hoa/thường (case-sensitive). Để replace case-insensitive, dùng Regex.Replace với RegexOptions.IgnoreCase.

Ví dụ: Regex.Replace

using System.Text.RegularExpressions;

string original = "Cricket Team";
string result = Regex.Replace(original, "t", "b", RegexOptions.IgnoreCase);
Console.WriteLine(result); // Crickeb beam (cả 't' và 'T' đều thành 'b')

Hàm helper tái sử dụng

public static class StringExtensions
{
    public static string ReplaceIgnoreCase(this string input, string oldValue, string newValue)
    {
        if (string.IsNullOrEmpty(input) || string.IsNullOrEmpty(oldValue))
            return input;
        
        return Regex.Replace(input, Regex.Escape(oldValue), newValue, RegexOptions.IgnoreCase);
    }
    
    // Overload cho char
    public static string ReplaceIgnoreCase(this string input, char oldChar, char newChar)
    {
        return input.ReplaceIgnoreCase(oldChar.ToString(), newChar.ToString());
    }
}

// Sử dụng
string s = "Hello World";
Console.WriteLine(s.ReplaceIgnoreCase("world", "C#")); // Hello C#
Console.WriteLine(s.ReplaceIgnoreCase('L', 'X'));      // HeXXo WorXd

Regex.Escape - Quan trọng!

Luôn dùng Regex.Escape(oldValue) để treat oldValue như literal string, không phải regex pattern. Tránh lỗi khi oldValue chứa ký tự đặc biệt (., *, ?, [, ], (, )...).

Performance: StringBuilder + IndexOf (Nhanh hơn Regex cho replace all)


public static string ReplaceIgnoreCaseFast(this string input, string oldValue, string newValue)
{
    if (string.IsNullOrEmpty(input) || string.IsNullOrEmpty(oldValue))
        return input;

    var sb = new StringBuilder();
    int startIndex = 0;
    int index;
    
    while ((index = input.IndexOf(oldValue, startIndex, StringComparison.OrdinalIgnoreCase)) >= 0)
    {
        sb.Append(input, startIndex, index - startIndex);
        sb.Append(newValue);
        startIndex = index + oldValue.Length;
    }
    sb.Append(input, startIndex, input.Length - startIndex);
    return sb.ToString();
}

So sánh hiệu suất (100k iterations, string 100 chars)

Phương phápThời gian (ms)Ghi chú
string.Replace (case-sensitive)~5 msBaseline
Regex.Replace (IgnoreCase)~120 msChậm do regex engine
StringBuilder + IndexOf (OrdinalIgnoreCase)~15 msNhanh, không allocation regex

Khi nào dùng cái nào?

  • Regex.Replace: Code đơn giản, ít gọi, pattern phức tạp (word boundary, regex).
  • StringBuilder + IndexOf: High performance, replace all trong loop, big data.
  • string.Replace: Case-sensitive, nhanh nhất.

Lưu ý: StringComparison.OrdinalIgnoreCase nhanh hơn CurrentCultureIgnoreCase và phù hợp cho ASCII/technical strings.