Supongamos que tengo el siguiente código en Python (sí, esta pregunta es sobre C#, esto es solo un ejemplo)
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" En esta cadena, reemplazaría {entry1} y {entry2} de la cadena a foo y bar usando .format()
De todos modos, puedo replicar EXACTAMENTE lo mismo en C# (y también eliminar las llaves) como el siguiente código:
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?usando la interpolación de cadenas podrías hacer lo siguiente
Dictionary<string, string> dict1 = new() { {"entry1", "foo"}, {"entry2", "bar"} }; string result = $"{dict1["entry1"]} {dict1["entry2"]} this is a string";Puede reemplazar valores dentro de {...} con la ayuda de expresiones regulares :
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);Salir:
foo bar this a stringPuede escribir un método de extensión para un diccionario y en él manipular su cadena según sus necesidades.
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; } }Ahora use este método de extensión para convertir la cadena dada a la cadena esperada,
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);El crédito de la lógica RegEx es para @Fabian Bigler . Aquí está la respuesta de Fabián:
Obtener valores entre llaves c#
prueba esto
foreach (var d in dict) str1=str1.Replace("{"+d.Key+"}",d.Value);o si te gustan las extensiones
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; }Puede usar un generador de cadenas si hay muchos elementos para reemplazar en una cadena
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(); }