本文介绍了用C#中的Dictionary中的值替换字符串中的单词的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个像这样的简单dictionary:

I have a simple dictionary like this:

var fruitDictionary = new Dictionary<string, string> {Apple,Fruit}, {Orange, Fruit}, {Spinach, Greens}

我有一个像

var fruitString = Apple Orange Spinach Orange Apple Spinach

如何用字典中的matching-word替换该句子中所有出现的特定单词?

How to replace all occurrences of the particular word in that sentence with the matching-word from the dictionary?

(即)上述句子应为Fruit Fruit Greens Fruit Fruit Fruit?

任何想法都值得赞赏.

我尝试过这样的事情:

var outputString = string.Empty;
fruitString.ToArray().ToList().Foreach(item =>
{
if (fruitDictionary.ContainsKey(item))
{
 outputString = outputString + fruitDictionary[item];

} 

有什么最佳解决方案吗?上面的代码不是最优的,因为它会traversing给定数组的整个长度!

Any optimal solution for this? The above code is not optimal because, it does traversing the entire-length of given array!

推荐答案

简单地:

var output = new StringBuilder(fruitString);

foreach (var kvp in fruitDictionary)
    output.Replace(kvp.Key, kvp.Value);

var result = output.ToString();

这简单地用fruitString初始化StringBuilder,并遍历Dictionary,将找到的每个键替换为值.

This simply initializes a StringBuilder with your fruitString, and iterates over the Dictionary, replacing each key it finds with the value.

这篇关于用C#中的Dictionary中的值替换字符串中的单词的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-18 12:59