在 StringBuilder 中替换字符串之前是否需要检查(使用“Contains”或“IndexOf”等函数)?
C# 中有 IndexOf 或 Contains 方法吗?下面是代码:
var sb = new StringBuilder(mystring);
sb.Replace("abc", "a");
string dateFormatString = sb.ToString();
if (sb.ToString().Contains("def"))
{
sb.Replace("def", "aa");
}
if (sb.ToString().Contains("ghi"))
{
sb.Replace("ghi", "assd");
}
正如您可能已经注意到的那样,我一次又一次地使用上面的 ToString() ,我想避免这种情况,因为它每次都会创建新的字符串。你能帮我看看我该如何避免吗?
Is there any method IndexOf or Contains in C#. Below is the code:
var sb = new StringBuilder(mystring);
sb.Replace("abc", "a");
string dateFormatString = sb.ToString();
if (sb.ToString().Contains("def"))
{
sb.Replace("def", "aa");
}
if (sb.ToString().Contains("ghi"))
{
sb.Replace("ghi", "assd");
}
As you might have noticed I am using ToString() above again and again which I want to avoid as it is creating new string everytime. Can you help me how can I avoid it?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
如果
StringBuilder
不包含“def”,那么执行替换不会导致任何问题,因此只需使用:If the
StringBuilder
doesn't contain "def" then performing the replacement won't cause any problems, so just use:StringBuilder
中没有这样的方法,但您不需要Contains
测试。您可以简单地这样写:如果没有找到
Replace
的第一个参数中的字符串,那么对Replace
的调用就是一个空操作——正是您想要的。文档指出:
你读这篇文章的方式是,当没有发生任何事情时,就什么也不做。
There's no such method in
StringBuilder
but you don't need theContains
tests. You can simply write it like this:If the string in the first parameter to
Replace
is not found then the call toReplace
is a null operation—exactly what you want.The documentation states:
The way you read this is that when there are no occurrences, nothing is done.
恕我直言,在这种情况下,您不必使用 StringBuilder...在循环中使用 StringBuilder 时更有用。就像微软在这篇文章中所说的那样
所以简单地你可以使用 String 并避免使用 ToString()...
IMHO you don't have to use StringBuilder in this case... StringBuilder is more useful when used in a loop. Like Microsoft say in In this article
So simply you can use String and avoid use ToString()...