I have multiple words I want to replace with values, whats the best way to do this?
Example: This is what I have done but it feels and looks so wrong
string s ="Dear <Name>, your booking is confirmed for the <EventDate>";
string s1 = s.Replace("<Name>", client.FullName);
string s2 =s1.Replace("<EventDate>", event.EventDate.ToString());
txtMessage.Text = s2;
There has to be a better way?
thanks
Replace Multiple Characters in a String using replaceAll # To replace multiple characters in a string, chain multiple calls to the replaceAll() method, e.g. str. replaceAll('. ', '!
Use the translate() method to replace multiple different characters. You can create the translation table specified in translate() by the str. maketrans() . Specify a dictionary whose key is the old character and whose value is the new string in the str.
The JavaScript replace() method is used to replace any occurrence of a character in a string or the entire string.
You could use String.Format.
string.Format("Dear {0}, your booking is confirmed for the {1}",
client.FullName, event.EventDate.ToString());
If you're planning on having a dynamic number of replacements, which could change at any time, and you want to make it a bit cleaner, you could always do something like this:
// Define name/value pairs to be replaced.
var replacements = new Dictionary<string,string>();
replacements.Add("<Name>", client.FullName);
replacements.Add("<EventDate>", event.EventDate.ToString());
// Replace
string s = "Dear <Name>, your booking is confirmed for the <EventDate>";
foreach (var replacement in replacements)
{
s = s.Replace(replacement.Key, replacement.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