Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

392
Views
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?
over 4 years ago · Santiago Trujillo
4 answers
Answer question

0

using string interpolation you could do the following

    Dictionary<string, string> dict1 = new() {
    {"entry1", "foo"},
    {"entry2", "bar"}
    };
    string result = $"{dict1["entry1"]} {dict1["entry2"]} this is a string";
over 4 years ago · Santiago Trujillo Report

0

You can replace values within {...} with a help of regular expressions:

  using System.Text.RegularExpressions;

  ...

  string str1 = "{entry1} {entry2} this a string";

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

  string result = Regex.Replace(str1, @"{([^}]+)}", 
      m => dict1.TryGetValue(m.Groups[1].Value, out var v) ? v : "???");

  // Let's have a look:
  Console.Write(result);

Outcome:

  foo bar this a string
over 4 years ago · Santiago Trujillo Report

0

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

over 4 years ago · Santiago Trujillo Report

0

try this

foreach (var d in dict) str1=str1.Replace("{"+d.Key+"}",d.Value);

or if you like the extensions

    Console.WriteLine(str1.FormatFromDictionary(dict));
    
public  static string FormatFromDictionary(this string str, Dictionary<string, string> dict)
{
        foreach (var d in dict) str = str.Replace("{" + d.Key + "}", d.Value);
        return str;
}

You can use a string builder if there are may items to replace in one string

public  static string FormatFromDictionary(this string str, Dictionary<string, string> dict)
{
        StringBuilder sb = new StringBuilder(str, 100);
        foreach (var d in dict) sb.Replace("{" + d.Key + "}", d.Value);
        return sb.ToString();
}
over 4 years ago · Santiago Trujillo Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!