Search code examples
c#dictionaryformat

Format string with dictionary in C#


Suppose I had the following code in Python (yes, this question is about c# this is just an example)

string = "{entry1} {entry2} this is a string"
dictionary = {"entry1": "foo", "entry2": "bar"}

print(string.format(**dictionary))

# output is "foo bar this is just a string"

In this string, it would replace the {entry1} and {entry2} from the string to foo and bar using the .format()

Is there anyway I can replicate this EXACT same thing in C# (and also remove the curly braces) like the following code:

string str1 = "{entry1} {entry2} this a string";
Dictionary<string, string> dict1 = new() {
    {"entry1", "foo"},
    {"entry2", "bar"}
};

// how would I format this string using the given dict and get the same output?

Solution

  • You can write an extension method for a dictionary and in it manipulate your string as per your need Like

    using System;
    using System.Collections.Generic;
    using System.Text.RegularExpressions;
    
    
    public static class DictionaryExtensions
    {
        public static string ReplaceKeyInString(this Dictionary<string, string> dictionary, string inputString)
        {
    
            var regex = new Regex("{(.*?)}");
            var matches = regex.Matches(inputString);
            foreach (Match match in matches)
            {
                var valueWithoutBrackets = match.Groups[1].Value;
                var valueWithBrackets = match.Value;
    
                if(dictionary.ContainsKey(valueWithoutBrackets))
                    inputString = inputString.Replace(valueWithBrackets, dictionary[valueWithoutBrackets]);
            }
    
            return inputString;
        }
    }
    

    Now use this extension method to convert given string to the expected string,

    string input = "{entry1} {entry2} this is a string";
    Dictionary<string, string> dictionary = new Dictionary<string, string> 
    { 
      { "entry1", "foo" }, 
      { "entry2", "bar" } 
    };
    
    var result = dictionary.ReplaceKeyInString(input);
    Console.WriteLine(result);
    

    RegEx logic credit goes to @Fabian Bigler. Here is Fabian's answer:

    Get values between curly braces c#


    Try online