# Friday, January 17, 2020

The C# string class provides a convenient method for replacing one string with another. The syntax is

string.Replace (<old string>, <new string>);

So the following code:

var oldName = "David";
var newName = "Mr. Giard";
var oldSentence = "My name is David";
var newSentence = oldSentence.Replace(oldName, newName);
  

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:

var oldName = "DAVID"; 
var newName = "Mr. Giard"; 
var oldSentence = "My name is David"; 
var newSentence = oldSentence.Replace(oldName, newName);
  

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:

var oldName = "DAVID"; 
var newName = "Mr. Giard"; 
var oldSentence = "My name is David"; 
var regex = new Regex(oldName, RegexOptions.IgnoreCase); 
var newSentence = regex.Replace(oldSentence, newName);
  

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.

C#