Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Should I use string.Contains() before string.Replace()?

Tags:

c#

.net

Is it unnecessary to have this if statement before doing a string replace?

 if (myString.Contains(oldValue))
 {
      myString = myString.Replace(oldValue, newValue);
 }
like image 894
Pat Migliaccio Avatar asked Dec 21 '15 20:12

Pat Migliaccio


People also ask

How do you replace a string in a string in Java without using replace method?

To replace a character in a String, without using the replace() method, try the below logic. Let's say the following is our string. int pos = 7; char rep = 'p'; String res = str. substring(0, pos) + rep + str.

Does string replace create a new string?

replace() Method. This method returns a new string resulting from replacing all occurrences of old characters in the string with new characters.

Which method can be used to replace parts of a string?

Python String replace() Method The replace() method replaces a specified phrase with another specified phrase.


1 Answers

All the details are in the documentation for String.Replace:

Return Value:
A string that is equivalent to the current string except that all instances of oldValue are replaced with newValue. If oldValue is not found in the current instance, the method returns the current instance unchanged.

The if statement is not required.

An if statement is not even a performance optimization, since String.Replace returns the same object instance, if oldValue is not found. I have verified this using the following code:

namespace StringReplaceTest
{
    class Program
    {
        static void Main(string[] args)
        {
            string s = "Test";
            string s2 = s.Replace("Foo", "Bar");
            string s3 = s.Replace("es", "tt");
        }
    }
}

Using the handy Make Object ID feature (right-click on a symbol in the Locals, Auto, or Watch window; see Common Expression Evaluator Features for more details) produced the following output:

s  | "Test" {$1}
s2 | "Test" {$1}
s3 | "Tttt" {$2}
like image 69
IInspectable Avatar answered Nov 15 '22 21:11

IInspectable