Feedback

Replace mit Dictionary

Sprache: C#

Dieses Snippet ersetzt in einem String jedes vorkommen eines Keys durch seinen ensprechenden Wert aus dem Dictionary. Der Aufruf ist eigentlich selbsterklärend: [code]Dictionary dict = new Dictionary<string, string> { {"(C)", "©"}, {"(TM)", "™"}, }; string old = "(C) 2013 Darius Arnold(TM)"; string new = ReplaceWithDictionary(old, dict);[/code] Ergibt folgendes: © 2013 Darius Arnold™
/// <summary>
/// Replaces each occurrence of a key of a dictionary in a string with the maching value.
/// </summary>
/// <param name="input">The text which should be edited.</param>
/// <param name="dict">The dictionary with the strings.</param>
/// <returns>The edited string.</returns>
private static string ReplaceWithDictionary(string input, Dictionary<String, String> dict)
{
    foreach (string s in dict.Keys)
        input = input.Replace(s, dict[s]);

    return input;
}
/// <summary>
/// Replaces each occurrence of a key of a dictionary in a string with the maching value.
/// </summary>
/// <param name="input">The text which should be edited.</param>
/// <param name="dict">The dictionary with the strings.</param>
/// <returns>The edited string.</returns>
private static string ReplaceWithDictionary(string input, Dictionary<String, String> dict)
{
    foreach (string s in dict.Keys)
        input = input.Replace(s, dict[s]);

    return input;
}

3 Kommentare

  1. Hallo, gute Idee, konnte ich auch gleich benutzen 🙂
    Ich würde jedoch keinen 2. String anlegen, da dieser mehr RAM verbraucht, bei großen strings können das schon ein paar MB sein.

  2. Danke.
    Wie würdest du es machen?
    schließlich kann ich input ja nicht ändern oder was zuweisen.. Oder?!