用另一个替换单词集

yas*_*uru -1 c# replace

我知道如何使用以下代码替换段落或文本文件中的另一个特定单词:

String output = input.Replace("oldvalue","newvalue");
Run Code Online (Sandbox Code Playgroud)

但我混淆了更换替换词组.我有近1000个单词要替换.例如:

" aback " => " ashamed ",
" abacus " => " abacus ",
" abaft " => " aback ",
" abandon " => " carelessness ",
" abandoned " => " alone ",
Run Code Online (Sandbox Code Playgroud)

因此,如果段落包含aback我想用ashamed每个单词替换它的单词.我们怎么做?谁能给我一个想法?

Ehs*_*san 10

您可以编写这样的扩展方法

public static string ReplaceSetOfStrings(this string input, Dictionary<string, string> pairsToReplace)
{
    foreach (var wordToReplace in pairsToReplace)
    {
        input = input.Replace(wordToReplace.Key, wordToReplace.Value);
    }
    return input;
}
Run Code Online (Sandbox Code Playgroud)

In the above method Dictionary key will contain the word that needs to be replaced with the word to be replcaed with in the value.

Then you can call it like this

Dictionary<string,string> pairsToBeReplaced = new Dictionary<string,string>();
pairsToBeReplaced.Add(" aback "," ashamed ");
input.ReplaceSetOfStrings(pairsToBeReplaced);
Run Code Online (Sandbox Code Playgroud)