簡體   English   中英

用c#中的Dictionary替換字符串中的單詞

[英]Replacing words in a string with values from Dictionary in c#

我有一個這樣的簡單dictionary

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

我有一個字符串

var fruitString = Apple Orange Spinach Orange Apple Spinach

如何用字典中的matching-word替換該句子中所有出現的特定單詞?

(即)上面的句子應該是Fruit Fruit Greens Fruit Fruit Fruit

任何想法都非常感謝。

編輯:

我試過這樣的事情:

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

} 

對此有何最佳解決方案? 上面的代碼不是最優的,因為它確實traversing給定數組的整個長度!

只是:

var output = new StringBuilder(fruitString);

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

var result = output.ToString();

這只是用您的fruitString初始化StringBuilder ,並遍歷Dictionary ,用值替換它找到的每個鍵。

嘗試此解決方案:

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));
    }
}

如果您有長字符串和大字典,那么基於查找和替換的解決方案會更快。

一些平滑的代碼:

var result = string.Join(" ", 
    string.Split(new[] { ' ' }, StringSplitOptions.RemoveEmptyEntries).Select(
        i => fruitDictionary.ContainsKey(i) ? fruitDictionary[i] : i);

應該是O(n*2m) - 其中n是要分割它的字符串的遍歷和2m - 通過Select()進行單詞替換的遍歷的1 m和結果的string.Join參數的另一個m 鑒於它是線性的,它應該適當地擴展。

要進一步縮放,如果輸入字符串不是唯一的,請將此方法的輸出緩存到Dictionary<string, string>中的輸入 - 這將為重復輸入產生大致O(1)

靈感來自MSDN Replace MatchEvaluator Delegate和@ Haney的答案,但沒有不切實際的“分裂”。

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);
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM