在 C# 中使用字典格式化字符串
Format string with dictionary in C#
假设我在Python中有以下代码(是的,这个问题是关于c#的,这只是一个例子)
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"
在此字符串中,它将使用 .format()
将字符串中的 {entry1} 和 {entry2} 替换为 foo 和 bar
我是否可以像下面的代码一样在 C# 中复制完全相同的东西(并删除花括号):
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?
使用字符串插值,您可以执行以下操作
Dictionary<string, string> dict1 = new() {
{"entry1", "foo"},
{"entry2", "bar"}
};
string result = $"{dict1["entry1"]} {dict1["entry2"]} this is a string";
您可以借助 正则表达式 :
替换 {...}
中的值
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);
结果:
foo bar this a string
您可以为字典编写一个 extension method 并在其中根据您的需要操作您的字符串 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;
}
}
现在使用此扩展方法将给定字符串转换为预期字符串,
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 逻辑归功于 @Fabian Bigler。这是 Fabian 的回答:
Get values between curly braces c#
试试这个
foreach (var d in dict) str1=str1.Replace("{"+d.Key+"}",d.Value);
或者如果您喜欢扩展程序
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;
}
如果一个字符串中有许多项要替换,您可以使用字符串生成器
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();
}
假设我在Python中有以下代码(是的,这个问题是关于c#的,这只是一个例子)
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"
在此字符串中,它将使用 .format()
我是否可以像下面的代码一样在 C# 中复制完全相同的东西(并删除花括号):
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?
使用字符串插值,您可以执行以下操作
Dictionary<string, string> dict1 = new() {
{"entry1", "foo"},
{"entry2", "bar"}
};
string result = $"{dict1["entry1"]} {dict1["entry2"]} this is a string";
您可以借助 正则表达式 :
替换{...}
中的值
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);
结果:
foo bar this a string
您可以为字典编写一个 extension method 并在其中根据您的需要操作您的字符串 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;
}
}
现在使用此扩展方法将给定字符串转换为预期字符串,
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 逻辑归功于 @Fabian Bigler。这是 Fabian 的回答:
Get values between curly braces c#
试试这个
foreach (var d in dict) str1=str1.Replace("{"+d.Key+"}",d.Value);
或者如果您喜欢扩展程序
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;
}
如果一个字符串中有许多项要替换,您可以使用字符串生成器
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();
}