20

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

SwDevMan81
  • 48,814
  • 22
  • 151
  • 184
David
  • 1,435
  • 4
  • 13
  • 17
  • 3
    I recommend something more exotic for the replacement string markers, like $$VAL$$ instead of , as it is possible some day that the message may actually need to have XML-like content. – Mike Atlas Jan 21 '11 at 21:17

8 Answers8

24

You could use String.Format.

string.Format("Dear {0}, your booking is confirmed for the {1}", 
   client.FullName, event.EventDate.ToString());
SwDevMan81
  • 48,814
  • 22
  • 151
  • 184
  • 2
    +1, also here's why it's a good idea: http://stackoverflow.com/questions/4671610/why-use-string-format/4671668#4671668 – Moo-Juice Jan 21 '11 at 20:48
  • The text is specified by the user for a report, is their so they know they dont have to write the client name, and the system will pull the object and replace the <> with values. – David Jan 21 '11 at 20:54
  • 1
    formatting would be good to use, for string.Format("Dear {0}, your booking is confirmed for the {1}", client.FullName, event.EventDate.ToString()); But the text is custome(by the user) so you dont know where the text will appear so you cannot use the format option. – David Jan 22 '11 at 07:48
15

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);
}
George Johnston
  • 31,652
  • 27
  • 127
  • 172
  • 1
    why you use dictionary instead of array ? – onmyway133 Nov 07 '12 at 10:05
  • 1
    @Yamamoto The example uses a dictionary to do a key-value look up on the indicator word, such as '', and replace it with the associated value 'client.FullName'. A simple one dimensional array wouldn't fit here. – George Johnston Nov 07 '12 at 13:47
11

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();
ThisGuy
  • 2,335
  • 1
  • 28
  • 34
  • I like this answer. It is much more efficient than the other suggestions if the input string is very large and there are a lot of tokens. – MikeD Feb 12 '13 at 16:13
4

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.

Evan Mulawski
  • 54,662
  • 15
  • 117
  • 144
3

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.

Gonzalo.-
  • 12,512
  • 5
  • 50
  • 82
Vadim
  • 394
  • 1
  • 7
3

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";

Hamad
  • 5,096
  • 13
  • 37
  • 65
2

Use String.Format:

const string message = "Dear {0}, Please call {1} to get your {2} from {3}";
string name = "Bob";
string callName = "Alice";
string thingy = "Book";
string thingyKeeper = "Library";
string customMessage = string.Format(message, name, callName, thingy, thingyKeeper);
Mike Atlas
  • 8,193
  • 4
  • 46
  • 62
1

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);
cwallenpoole
  • 79,954
  • 26
  • 128
  • 166
Amit Philips
  • 387
  • 6
  • 17