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

Should I have this if statement before replacing the string?

 if (myString.Contains(oldValue))
 {
      myString = myString.Replace(oldValue, newValue);
 }
+4
source share
2 answers

All details are in the documentation for String.Replace :

Return value:
A string 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.

ifNo operator required.

if , String.Replace , oldValue . , :

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

" " ( " ", "" "", . ) :

s  | "Test" {$1}
s2 | "Test" {$1}
s3 | "Tttt" {$2}
+9

String.Replace() , , . .

+3

Source: https://habr.com/ru/post/1621163/


All Articles