Search code examples
c#stringfilterreplaceblacklist

Filtering bad words


.Net version is 4.7.1 (no have third argument of string.Replace with ignorecase)

badwords = ["home", ...]
text = "Home, hhhome HOME, HOme Hhome1212, H o M e"
expected result: "****, hh**** ****, **** H****1212, *******"

It is necessary to ignore the case of the text while maintaining its original case

public string Filter(string text)
{
    foreach (var badword in _badwords)
    {
        text = text.Replace(badword, new string('*', badword.Length));
    }

    return text;
}

Solution

  • Just pass the third argument to the string.Replace method and specify it as StringComparison.CurrentCultureIgnoreCase or StringComparison.InvariantCultureIgnoreCase or StringComparison.OrdinalIgnoreCase.