简体   繁体   中英

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.

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.

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 .

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. .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.

The high cost here is 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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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