替换字符串中的多个单词
我有多个单词我想用值替换,最好的方法是什么?
示例:这就是我所做的,但感觉和看起来都错了
string s ="Dear , your booking is confirmed for the "; string s1 = s.Replace("", client.FullName); string s2 =s1.Replace("", event.EventDate.ToString()); txtMessage.Text = s2;
一定有更好的方法?
谢谢
如果你计划有一个动态数量的替换,可以随时改变,并且你想让它更清洁,你总是可以做这样的事情:
// Define name/value pairs to be replaced. var replacements = new Dictionary(); replacements.Add("", client.FullName); replacements.Add("", event.EventDate.ToString()); // Replace string s = "Dear , your booking is confirmed for the "; foreach (var replacement in replacements) { s = s.Replace(replacement.Key, replacement.Value); }
你可以使用String.Format 。
string.Format("Dear {0}, your booking is confirmed for the {1}", client.FullName, event.EventDate.ToString());
要建立在George的答案之上,您可以将消息解析为令牌,然后从令牌构建消息。
如果模板字符串更大并且有更多令牌,那么这将更有效,因为您没有为每个令牌替换重建整个消息。 此外,令牌的生成可以移出到Singleton中,因此只执行一次。
// Define name/value pairs to be replaced. var replacements = new Dictionary(); replacements.Add("", client.FullName); replacements.Add("", event.EventDate.ToString()); string s = "Dear , your booking is confirmed for the "; // 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();
您可以将Replace操作链接在一起:
s = s.Replace(...).Replace(...);
请注意,您不需要创建其他字符串来执行此操作。
使用String.Format是合适的方法,但前提是您可以更改原始字符串以适应大括号格式。
当你进行多次替换时,使用StringBuilder
而不是string更有效。 否则,每次运行时,replace函数都会复制字符串,浪费时间和内存。
使用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);
试试这段代码:
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";
改进@Evan所说的……
string s ="Dear , your booking is confirmed for the "; string s1 = client.FullName; string s2 = event.EventDate.ToString(); txtMessage.Text = s.Replace("", s1).Replace("EventDate", s2);
- 使用EF在MVC应用程序中发生System.Data.Entity.Core.EntityCommandExecutionException
- 与WindowsFormsHost绑定
- UWP:为什么我可以通过后台任务(使用TimeTrigger)超过CPU配额?
- 有jQuery倒计时的问题? functionserverSync:serverTime
- wcf配置文件vs代码配置的优点和缺点
- C#EF Code First虚拟关键字,它有什么作用?
- 捕获每个WPF MediaElement框架
- C#| WPF – 自定义标题栏 – 最大化时从顶部拖动窗口不起作用
- entity framework中的提供者连接字符串