Ignore case in String.Replace using StringComparison.OrdinalIgnoreCase

Views: 3729
Comments: 0
Like/Unlike: 1
Posted On: 27-May-2021 06:08 

Share:   fb twitter linkedin
Smith
None
2568 Points
74 Posts


.Net Core 2.0 and higher has native method String.Replace that supports StringComparison. The StringComparison has the OrdinalIgnoreCase property and it treats the characters in the strings to compare as if they were converted to uppercase (using the conventions of the invariant culture) and then it performs a simple byte comparison  and it is independent of language. 

This is most useful when replacing strings that are generated programmatically or when comparing case-insensitive resources such as paths and filenames.

 

Definition

We have following two overload methods:

public string Replace (string oldValue, string newValue, StringComparison comparisonType);
public string Replace (string oldValue, string newValue, bool ignoreCase, System.Globalization.CultureInfo culture);

Parameters

  • oldValue String
    The string to be replaced.
  • newValue String
    The string to replace all occurrences of oldValue.
  • comparisonType StringComparison
    One of the enumeration values that determines how oldValue is searched within this instance.
  • Returns String
    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.

So we can use either like this:

Example I)

var str1 = "A".Replace("a", "b", StringComparison.CurrentCultureIgnoreCase);
var str2 = "A".Replace("a", "b", true, CultureInfo.CurrentCulture);

Console.WriteLine($"str1: {str1}");
Console.WriteLine($"str2: {str2}");

Out put:

Example II)

var str1 = "AbcD".Replace("abcd", "xyz", StringComparison.CurrentCultureIgnoreCase);
var str2 = "AbcD".Replace("abcd", "xyz", true, CultureInfo.CurrentCulture);

Console.WriteLine($"str1: {str1}");
Console.WriteLine($"str2: {str2}");

Out put:

0 Comments
 Log In to Chat