我想要用值替换多个单词,最好的方法是什么?
实施例: 这就是我所做的,但感觉和看起来错了
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;
必须有更好的方法吗?
感谢
答案 0 :(得分:23)
您可以使用String.Format。
string.Format("Dear {0}, your booking is confirmed for the {1}",
client.FullName, event.EventDate.ToString());
答案 1 :(得分: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);
}
答案 2 :(得分: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();
答案 3 :(得分:4)
您可以将替换操作链接在一起:
s = s.Replace(...).Replace(...);
请注意,您无需创建其他字符串即可。
使用String.Format是合适的方法,但前提是您可以更改原始字符串以适应大括号格式。
答案 4 :(得分:3)
当你进行多次替换时,使用StringBuilder
而不是字符串会更有效率。否则,每次运行时,replace函数都会复制字符串,浪费时间和内存。
答案 5 :(得分:2)
使用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);
答案 6 :(得分:2)
试试这段代码:
string MyString ="This is the First Post to Stack overflow";
MyString = MyString.Replace("the", "My").Replace("to", "to the");
结果:MyString ="This is My First Post to the Stack overflow";
答案 7 :(得分:1)
改进@Evan所说的......
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);