The C# string class provides a convenient method for replacing one string with another. The syntax is
So the following code:
stores the value "My name is Mr. Giard" in the variable newSentence.
It is simple and it works. But I recently discovered a limitation: Searching for the old string is always case-sensitive. If I want to do a case-insensitive search and replace instances of "David" or "david" or "DAVID" (or even "daVid"), the string.Replace method does not support this.
The following code:
Results in the value "My name is David" being assigned to newSentence. In other words, the Replace method did nothing.
Fortunately, I can use the regular expression library to do this. The code is below:
It is only one more line than using Replace and it allows for much more flexibility. And, as Regular Expressions go, this one is quite simple.