Is it unnecessary to have this if statement before doing a string replace?
if (myString.Contains(oldValue))
{
myString = myString.Replace(oldValue, newValue);
}
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.
replace() Method. This method returns a new string resulting from replacing all occurrences of old characters in the string with new characters.
Python String replace() Method The replace() method replaces a specified phrase with another specified phrase.
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}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With