Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C# How to replace the variables inside strings [duplicate]

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

I got string from database string with some variables. I know string.format() or $"" to replace, but that can't solve.

The result I want to get is like

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

How can I get this?

like image 493
Theleme Pan Avatar asked Jun 17 '26 07:06

Theleme Pan


2 Answers

You can do it like this:

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

Or if you want to use String.Replace:

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

And if you want to use $:

var name = "name1";
var country = "country1";
var result = $"Hi {name}, Are you from {country}";
like image 100
gwt Avatar answered Jun 19 '26 21:06

gwt


You can try to Replace all {...} with a help of Regular Expressions:

  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 : "???");

Edit: If you want to remove {..} you can modify regular expression a bit:

string result = Regex.Replace(
   greet,
 @"\{(?<name>.*?)\}",
   match => replacements.TryGetValue(match.Groups["name"].Value, out var value) ? value : "???");   
like image 35
Dmitry Bychenko Avatar answered Jun 19 '26 22:06

Dmitry Bychenko



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!