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
You can chain the Replace operations together:
s = s.Replace(...).Replace(...);
Note that you don't need to create other strings to do this.
Using String.Format is the appropriate way, but only if you can change the original string to suit the brace formatting.
When you do multiple replaces it's much more efficient to use StringBuilder
instead of string. Otherwise replace function is making a copy of the string every time you run it, wasting time and memory.
To build on George's answer, you could parse the message into tokens then build the message from the tokens.
If the template string was much larger and there are more tokens, this would be a tad more efficient as you are not rebuilding the entire message for each token replacement. Also, the generation of the tokens could be moved out into a Singleton so it is only done once.
// Define name/value pairs to be replaced.
var replacements = new Dictionary<string, string>();
replacements.Add("<Name>", client.FullName);
replacements.Add("<EventDate>", event.EventDate.ToString());
string s = "Dear <Name>, your booking is confirmed for the <EventDate>";
// Parse the message into an array of tokens
Regex regex = new Regex("(<[^>]+>)");
string[] tokens = regex.Split(s);
// Re-build the new message from the tokens
var sb = new StringBuilder();
foreach (string token in tokens)
sb.Append(replacements.ContainsKey(token) ? replacements[token] : token);
s = sb.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);
}
Try this code:
string MyString ="This is the First Post to Stack overflow";
MyString = MyString.Replace("the", "My").Replace("to", "to the");
Result: MyString ="This is My First Post to the Stack overflow";
Improving on what @Evan said...
string s ="Dear <Name>, your booking is confirmed for the <EventDate>";
string s1 = client.FullName;
string s2 = event.EventDate.ToString();
txtMessage.Text = s.Replace("<Name>", s1).Replace("EventDate", s2);