问题描述
我有一个简单的 dictionary
像这样:
varfruitDictionary = new Dictionary{Apple,Fruit}, {Orange, Fruit}, {Spinach, Greens}
我有一个像
这样的字符串varfruitString = Apple Orange Spinach Orange Apple Spinach
如何用字典中的匹配词
替换该句子中所有出现的特定词?
(即)上面的句子应该是Fruit Fruit Greens Fruit Fruit Fruit
?
非常感谢任何想法.
我尝试过这样的事情:
var outputString = string.Empty;FruitString.ToArray().ToList().Foreach(item =>{if (fruitDictionary.ContainsKey(item)){outputString = outputString + FruitDictionary[item];}
对此有什么最佳解决方案吗?上面的代码不是最优的,因为它遍历
给定数组的整个长度!
简单:
var output = new StringBuilder(fruitString);foreach(fruitDictionary 中的 var kvp)output.Replace(kvp.Key, kvp.Value);var 结果 = output.ToString();
这只是用你的 fruitString
初始化一个 StringBuilder
,并遍历 Dictionary
,用值替换它找到的每个键.>
I have a simple dictionary
like this:
var fruitDictionary = new Dictionary<string, string> {Apple,Fruit}, {Orange, Fruit}, {Spinach, Greens}
and I have a string like
var fruitString = Apple Orange Spinach Orange Apple Spinach
How to replace all occurrences of the particular word in that sentence with the matching-word
from the dictionary?
(i.e.) The above sentence should read Fruit Fruit Greens Fruit Fruit Fruit
?
Any ideas is much appreciated.
EDIT:
I tried something like this:
var outputString = string.Empty;
fruitString.ToArray().ToList().Foreach(item =>
{
if (fruitDictionary.ContainsKey(item))
{
outputString = outputString + fruitDictionary[item];
}
Any optimal solution for this? The above code is not optimal because, it does traversing
the entire-length of given array!
Simply:
var output = new StringBuilder(fruitString);
foreach (var kvp in fruitDictionary)
output.Replace(kvp.Key, kvp.Value);
var result = output.ToString();
This simply initializes a StringBuilder
with your fruitString
, and iterates over the Dictionary
, replacing each key it finds with the value.
这篇关于用c#中字典中的值替换字符串中的单词的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!