How do I make "Replace" replace all occurrences of a word regardless of case?

6

The Replace function replaces all occurrences of a word or expression, but is case sensitive:

string str = "Hello WorLLd";//Substitui só os 'l' e não o 'L'
str = str.Replace("l", "EL");
Console.WriteLine("My string: " + str);

Output:

My string: HeELELo WorLLd

I would like the output to be:

My string: HeELELo WorELELd
    
asked by nbro 11.09.2014 в 23:16

2 answers

7

You can use Regex.Replace . Something like this:

string str = "Hello WorLLd"; //Substitui só os 'l' e não o 'L'
str = Regex.Replace(str, "l", "EL", RegexOptions.IgnoreCase);
Console.WriteLine("My string: " + str);

For those of you who do not like Regex , I found this solution on a answer in the OS :

public static string ReplaceString(string str, string oldValue, string newValue, StringComparison comparison = StringComparison.CurrentCultureIgnoreCase) {
    StringBuilder sb = new StringBuilder();
    int previousIndex = 0;
    int index = str.IndexOf(oldValue, comparison);
    while (index != -1) {
        sb.Append(str.Substring(previousIndex, index - previousIndex));
        sb.Append(newValue);
        index += oldValue.Length;
        previousIndex = index;
        index = str.IndexOf(oldValue, index, comparison);
    }
    sb.Append(str.Substring(previousIndex));
    return sb.ToString();
}

I placed GitHub for future reference .

The secret is the StringComparison enumeration. in IndexOf() . Usage:

ReplaceString("Hello WorLLd", "l", "EL")

You have another answer in SO which is a bit better as it is already an extension method for string e avoid a StringBuilder . But building while with break is unnecessary. Ideally I'd like to improve this, but it still seems like a better solution anyway.

public static class StringExtensions {
    public static string Replace(this string originalString, string oldValue, string newValue, StringComparison comparisonType) {
        int startIndex = 0;
        while (true) {
            startIndex = originalString.IndexOf(oldValue, startIndex, comparisonType);
            if (startIndex == -1)
                break;
            originalString = originalString.Substring(0, startIndex) + newValue + originalString.Substring(startIndex + oldValue.Length);
            startIndex += newValue.Length;
        }
        return originalString;
    }
}

I placed GitHub for future reference .

    
11.09.2014 / 23:36
2

Use this:

str = Regex.Replace(str, "l", "EL", RegexOptions.IgnoreCase);
    
11.09.2014 в 23:35