用清晰的单词不区分大小写替换文本c#

时间:2017-08-21 21:36:24

标签: c# replace case-insensitive

我有一个坏词列表,如果在文本字符串中找到,将被清理后的单词替换。 例如。 badwords{woof} is replaced by w$$f

但目前只在数组列表与句子中匹配的单词相同的情况下才有效。

var badWords = new List<string>{"woof", "meow"}

var string = "I have a cat named meow and a dog name Woof." 应该成为===“我有一只名为m $$ w的猫和一只名叫W $$ f的狗”

public string CensorText(string text)
    {
        if (string.IsNullOrWhiteSpace(text))
        {
            return text;
        }
        foreach (string word in CensoredWords)
        {
            text = text.Replace(word, WordCleaner(word));
        }
        return text;
    }

    private static string WordCleaner(string wordToClean)
    {
        string firstChar = wordToClean.Substring(0,1);
        string lastChar = wordToClean.Substring(wordToClean.Length - 1);
        string centerHash = new string('$', wordToClean.Length-2);

        return string.Concat(firstChar, centerHash, lastChar);         
    }

如何在循环显示单词并清理它们时使其不区分大小写。答案越简单就越简单。

2 个答案:

答案 0 :(得分:0)

尝试更换:

text = text.Replace(word, WordCleaner(word));

text = text.Replace(word.ToLower(), WordCleaner(word));

这会将任何大写字母转换为小写字母。

修改

我意识到我把错误的变量变成了小写。

变化:

public string CensorText(string text)
{

要:

public string CensorText(string text)
{
    text = text.ToLower();

编辑2

要保留更改了删失字词的原始句子,使用re会更容易。首先,将文件还原为问题中的文件。

现在替换:

text = text.Replace(word, WordCleaner(word));

使用:

text = regex.replace(text,word,WordCleaner(word),RegexOptions.Ignorecase);

答案 1 :(得分:0)

这是一个你可以使用的简单选项 好处是你不关心哪个词是小写的,它适用于任何一种情况。请注意,compare返回一个int,因此我们为什么要检查它的匹配为0。

string input = "the Woof is on Fire, we don't need no bucket, leT the ...";
string[] bad_words = new string[] {"woof","fire","BucKet", "Let"};

foreach (var word in input.Split(' ')) {
    if (bad_words.Any( b => String.Compare( word, b // Following line does what you want:
                                          , StringComparison.OrdinalIgnoreCase) == 0))
        Console.Write(WordCleaner(word));
    else
        Console.Write(word);
}

输出:

the W$$f is on F$$e  we don't need no b$$$$t  l$T the ... 

对我来说似乎很好。请注意,如果您在空格上进行拆分,则右后方带有逗号的单词将使用该逗号作为单词的一部分