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?
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}";
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 : "???");
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With