简体   繁体   English

我怎么知道String.Replace或StringBuilder.Replace是否会修改字符串?

[英]How can I know if String.Replace or StringBuilder.Replace will modify the string?

I want to know if I need to do String.Replace / StringBuilder.Replace on my string. 我想知道是否需要在字符串上执行String.Replace / StringBuilder.Replace

So I have two ways to do that. 因此,我有两种方法可以做到这一点。

The first way: 第一种方式:

var myString = new StringBuilder("abcd");
var copyMyString = myString;

myString = myString.Replace("a", "b");
if (!myString.Equals(copyMyString))//If the string Is changed
{
    //My Code
}

And the second: 第二个:

var pos = myString.ToString().IndexOf("a");
if (pos > 0)
{
    myString = myString.Replace("a", "b");
    //After this line the string is replaced.
    //My Code
 }

What is a faster way to do this (performance)? 什么是执行此操作(性能)的更快方法?

Is there another way to do that? 还有另一种方法吗?

The string length sometimes can be 1MB and more. 字符串长度有时可以是1MB或更多。

You can speed this up a little by modifying your second method like so: 您可以通过修改第二种方法来加快速度,如下所示:

var pos = myString.ToString().IndexOf("a");
if (pos > 0)
{
    myString = myString.Replace("a", "b", pos, myString.Length - pos);
    //After this line the string is replaced.
    //My Code
 }

We now call the overload of StringBuilder.Replace() which specifies a starting index . 现在,我们调用StringBuilder.Replace()的重载,该重载指定了起始索引

Now it doesn't need to search the first part of the string again. 现在,无需再次搜索字符串的第一部分。 This is unlikely to save much time though - but it will save a little. 不过,这不太可能节省很多时间-但会节省一些时间。

It depends how often pos > 0 (note that should probably be pos >= 0 ) is true. 这取决于pos > 0 (注意应该应该是pos >= 0 )为真的频率。 .IndexOf() will cycle through each character until it finds what you are looking for so it's O(n) , this is a pretty cheap operation since it's only a single search. .IndexOf()将循环遍历每个字符,直到找到您要查找的字符为止,所以它是O(n) ,这是一个非常便宜的操作,因为它仅是一次搜索。

The high cost here is String.Replace() . 这里的高成本是String.Replace() For strings modifying them often under can be overwriting the string, the larger the string the more costly that becomes. 对于经常在字符串下进行修改的字符串,可能会覆盖该字符串,字符串越大,成本越高。 This also can have several replaces since it finds all occurrences. 由于它可以找到所有出现的位置,因此也可以有多个替换。

So unless pos >= 0 is almost always true the second case will be more efficient but you should drop .ToString() as it's doing nothing. 因此,除非pos >= 0几乎始终为true ,否则第二种情况会更有效,但是您应该删除.ToString()因为它什么也不做。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM