The following algorithm is used to find a word from Blacklisted words in a string (called text) and replace these words with censored text, as shown in the example.
Example:
Blacklist ["bomb"]
text: "bomb bombs"
Output: "b*** bombs"
Code
public List<string> Blacklist { get; set; } = new List<string>();
public string CensorWord(string word)
{
if (Blacklist.Contains(word.ToLower()))
{
return String.Concat(word[0], new string('*', word.Length > 1 ? word.Length - 1 : 1));
}
else
{
return word;
}
}
public string CensorText(string text)
{
string result = text;
foreach(string bannedWord in Blacklist) //Can I get rid of this foreach?
{
string pattern = String.Format(@"\b{0}\b", bannedWord);
result = Regex.Replace(result, pattern, CensorWord(bannedWord));
}
return result;
}
How can I optimize my code? I don't care about edge cases.