问题
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!
回答1:
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.
回答2:
Try this solution:
internal class Program
{
public static void Main(string[] args)
{
var fruitDictionary = new Dictionary<string, string>
{
{"Apple", "Fruit"},
{"Orange", "Fruit"},
{"Spinach", "Greens"}
};
var fruitString = "Apple Orange Spinach Orange Apple Spinach";
var result = string.Join(" ",
fruitString.Split(' ').Select(i => fruitDictionary.ContainsKey(i) ? fruitDictionary[i] : i));
}
}
This will be faster that find-and-replace based solutions if you have long strings and large dictionaries.
回答3:
Some smooth code for this:
var result = string.Join(" ",
string.Split(new[] { ' ' }, StringSplitOptions.RemoveEmptyEntries).Select(
i => fruitDictionary.ContainsKey(i) ? fruitDictionary[i] : i);
Should be O(n*2m)
- where n
is the traversal of string to split it and 2m
- one m
for the traversal that does the word replacement via Select()
and another m
for the string.Join
parameter of the results. Given that it is linear, it should scale decently.
To scale further, if your input string are not unique, cache the outputs of this method against the inputs in a Dictionary<string, string>
- this will yield roughly O(1)
for repeated inputs.
回答4:
Inspired by the MSDN Replace MatchEvaluator Delegate and @Haney's answer but with out the unrealistic 'Split'.
using System.Collections;
void Main()
{
var args = new Dictionary<string, string> {
{"Fruit1","Apple"},
{"Fruit2", "Orange"},
{"Greens", "Spinach"}
};
var output = Regex.Replace(
"Hi, my Fav fruits are {Fruit1} and {Fruit2}. I like {Papaya}",
@"\{(\w+)\}", //replaces any text surrounded by { and }
m =>
{
string value;
return args.TryGetValue(m.Groups[1].Value, out value) ? value : "null";
}
);
Console.WriteLine(output);
}
来源:https://stackoverflow.com/questions/19899280/replacing-words-in-a-string-with-values-from-dictionary-in-c-sharp