如何使用C#替换字符串中的多个单词?

use*_*567 8 c# string

我想知道如何从字符串中替换(删除)多个单词(如500+).我知道我可以使用替换功能为单个单词执行此操作,但如果我想替换500多个单词怎么办?我有兴趣从文章中删除所有通用关键字(例如"和","我","你"等).

这是1替换的代码..我想做500+ ..

        string a = "why and you it";
        string b = a.Replace("why", "");
        MessageBox.Show(b);
Run Code Online (Sandbox Code Playgroud)

谢谢

@ Sergey Kucher文字大小会在几百字到几千字之间变化.我正在从随机文章中取代这些词.

xan*_*tos 8

我通常会这样做:

// If you want the search/replace to be case sensitive, remove the 
// StringComparer.OrdinalIgnoreCase
Dictionary<string, string> replaces = new Dictionary<string, string>(StringComparer.OrdinalIgnoreCase) { 
    // The format is word to be searched, word that should replace it
    // or String.Empty to simply remove the offending word
    { "why", "xxx" }, 
    { "you", "yyy" },
};

void Main()
{
    string a = "why and you it and You it";

    // This will search for blocks of letters and numbers (abc/abcd/ab1234)
    // and pass it to the replacer
    string b = Regex.Replace(a, @"\w+", Replacer);
}

string Replacer(Match m)
{
    string found = m.ToString();

    string replace;

    // If the word found is in the dictionary then it's placed in the 
    // replace variable by the TryGetValue
    if (!replaces.TryGetValue(found, out replace))
    {
        // otherwise replace the word with the same word (so do nothing)
        replace = found;
    }
    else
    {
        // The word is in the dictionary. replace now contains the
        // word that will substitute it.

        // At this point you could add some code to maintain upper/lower 
        // case between the words (so that if you -> xxx then You becomes Xxx
        // and YOU becomes XXX)
    }

    return replace;
}
Run Code Online (Sandbox Code Playgroud)

正如其他人写的那样,但是没有子串的问题(ass原则......你不想ass从cl中删除asses :-)),只有在你只需要删除单词时才能工作:

var escapedStrings = yourReplaces.Select(Regex.Escape);
string result = Regex.Replace(yourInput, @"\b(" + string.Join("|", escapedStrings) + @")\b", string.Empty);
Run Code Online (Sandbox Code Playgroud)

我使用\b边界这个词......解释它是什么有点复杂,但找到单词边界很有用:-)


Vau*_*lts 0

创建您想要的所有文本的列表并将其加载到列表中,您可以执行此操作相当简单或变得非常复杂。一个简单的例子是:

var sentence = "mysentence hi";
var words = File.ReadAllText("pathtowordlist.txt").Split(Enviornment.NewLine);
foreach(word in words)
   sentence.replace("word", "x");
Run Code Online (Sandbox Code Playgroud)

如果您想要双重映射方案,您可以创建两个列表。