Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Replace multiple words in string

Tags:

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

like image 620
David Avatar asked Jan 21 '11 20:01

David


People also ask

How do I replace multiples in a string?

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('. ', '!

How do you replace multiple words in a string in Python?

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.

How do you change multiple words in HTML?

The JavaScript replace() method is used to replace any occurrence of a character in a string or the entire string.


2 Answers

You could use String.Format.

string.Format("Dear {0}, your booking is confirmed for the {1}", 
   client.FullName, event.EventDate.ToString());
like image 147
SwDevMan81 Avatar answered Sep 21 '22 06:09

SwDevMan81


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);
}
like image 32
George Johnston Avatar answered Sep 18 '22 06:09

George Johnston