What is an alternative to string.Replace that is case-insensitive in C#?

CsharpServer Side ProgrammingProgramming

Replace() method is a string method. This method is used to replace all the specified Unicode characters or specified string from the current string object and returns a new modified string. This method can be overloaded by passing arguments to it.

Example 1

To replace even the case sensitive charaters Regular expressions provide a powerful, flexible, and efficient method for processing text. The extensive pattern-matching notation of regular expressions enables you to quickly parse large amounts of text to:

  • Find specific character patterns.

  • Validate text to ensure that it matches a predefined pattern (such as an email address).

  • Extract, edit, replace, or delete text substrings.

  • Add extracted strings to a collection in order to generate a report.

Example 2

class Program{
   static void Main(string[] args){
      String str = "Cricket Team";
      Console.WriteLine("OldString : " + str);
      Console.WriteLine("NewString: " + str.Replace('e', 'E'));
      Console.WriteLine("\nOldString: " + str);
      Console.ReadLine();
   }
}

Output

OldString : Cricket Team
NewString: CrickEt TEam
OldString: Cricket Team

Example 3

static void Main(string[] args){
   String str = "Cricket Team";
   Console.WriteLine("OldString : " + str);{
      Console.WriteLine("NewString: " + CaseInsenstiveReplace("Cricket Team", "t", "b"));
      Console.WriteLine("\nOldString: " + str);
      Console.ReadLine();
   }
   static string CaseInsenstiveReplace(string originalString, string oldValue, string newValue){
      Regex regEx = new Regex(oldValue,
      RegexOptions.IgnoreCase | RegexOptions.Multiline);
      return regEx.Replace(originalString, newValue);
   }
}

Output

OldString : Cricket Team
NewString: Crickeb beam
OldString: Cricket Team
raja
Published on 07-Nov-2020 11:59:58
Advertisements