How to make "Replace" replace all occurrences of a word without taking uppercase or lowercase?

Asked

Viewed 2,337 times

7

The function Replace supersedes all occurrences of a word or expression, but taking into account uppercase and lowercase:

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

2 answers

7


You can use the Regex.Replace(). Something like that:

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 who don’t like Regex, found this solution in a response 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 put in the Github for future reference.

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

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

There’s another response in the OS which is a little better by already being an extension method for string and avoid a StringBuilder. But the construction of whilewith break is unnecessary. The ideal would be to improve this, but it still seems to me 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 put in the Github for future reference.

  • @Cell for simple things the RegEx It’s very simple. It complicates a bit for more sophisticated wedding patterns. Although it’s not a seven-headed bug either. In cases where performance is important Regex can become a burden.

2

Use like this:

str = Regex.Replace(str, "l", "EL", RegexOptions.IgnoreCase);

Browser other questions tagged

You are not signed in. Login or sign up in order to post.