C#如何替换字符串中的变量

C# How to replace the variables inside strings

string name = "name1";
string country = "country1";
string greet = "Hi {name}, Are you from {country}";

我从数据库中得到了字符串 带有一些变量的字符串。 我知道 string.format()$"" 可以替换, 但那无法解决。

我想要得到的结果就像

string result = $"Hi {name}, Are you from {country}";

我怎样才能得到这个?

你可以这样做:

string name = "name1";
string country = "country1";
string result = String.Format("Hi {0}, Are you from {1}",name, country);

或者如果你想使用 String.Replace:

string name = "name1";
string country = "country1";
string result = greet.Replace("{name}",name).Replace("{country}",country);

如果你想使用 $:

var name = "name1";
var country = "country1";
var result = $"Hi {name}, Are you from {country}";

如果只想替换多个变量,可以按列表迭代:

string greet = "Hi {name}, Are you from {country}";
var placeholders = new List<(string placeholder, string value)>()
{
    ("name", "name1"),
    ("country1", "country1")
};

foreach (var ph in placeholders)
    greet = greet.Replace($"{{{ph.placeholder}}}", ph.value);

您可以尝试 Replace 所有 {...} 借助 正则表达式 :

  using System.Text.RegularExpressions;

  ...

  // All possible substitutions (from database?)
  Dictionary<string, string> replacements = 
    new Dictionary<string, string>(StringComparer.OrdinalIgnoreCase) {
      { "name", "name1"},
      { "country", "country1"},
  };

  string greet = "Hi {name}, Are you from {country}";

  string result = Regex.Replace(
      greet,
    @"(?<=\{).*?(?=\})",
      match => replacements.TryGetValue(match.Value, out var value) ? value : "???");