替换字符串中的多个单词

Dav*_*vid 20 c#

我有多个单词我想用值替换,最好的方法是什么?

示例:这就是我所做的,但感觉和看起来都错了

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;
Run Code Online (Sandbox Code Playgroud)

一定有更好的方法?

谢谢

SwD*_*n81 23

你可以使用String.Format.

string.Format("Dear {0}, your booking is confirmed for the {1}", 
   client.FullName, event.EventDate.ToString());
Run Code Online (Sandbox Code Playgroud)

  • +1,这也是为什么这是一个好主意:http://stackoverflow.com/questions/4671610/why-use-string-format/4671668#4671668 (2认同)

Geo*_*ton 15

如果你计划有一个动态数量的替换,可以随时改变,并且你想让它更清洁,你总是可以这样做:

// 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);
}
Run Code Online (Sandbox Code Playgroud)


Thi*_*Guy 10

要建立在George的答案之上,您可以将消息解析为令牌,然后从令牌构建消息.

如果模板字符串更大并且有更多令牌,那么这将更有效,因为您没有为每个令牌替换重建整个消息.此外,令牌的生成可以移出到Singleton中,因此只执行一次.

// 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();
Run Code Online (Sandbox Code Playgroud)