Is there a case insensitive string replace in .Net without using Regex?

前端 未结 9 1633
天涯浪人
天涯浪人 2020-12-11 00:45

I recently had to perform some string replacements in .net and found myself developing a regular expression replacement function for this purpose. After getting it to work I

9条回答
  •  旧巷少年郎
    2020-12-11 01:21

    Update in .NET Core 2.0+ (August 2017)

    This is natively available in .NET Core 2.0+ with String.Replace which has the following overloads

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

    So you can use either like this:

    "A".Replace("a", "b", StringComparison.CurrentCultureIgnoreCase);
    "A".Replace("a", "b", true, CultureInfo.CurrentCulture);
    

    PS: You can browse .NET Core source if you want to see how MS implemented it


    Legacy .NET Framework 4.8- option for VB Projects

    Visual Basic has an Option Compare setting which can be set to Binary or Text

    Setting to Text will make all string comparisons across your project case insensitive by default.

    So, as other answers have suggested, if you are pulling in the Microsoft.VisualBasic.dll, when calling Strings.Replace if you don't explicitly pass a CompareMethod the method will actually defer to the Compare option for your file or project using the [OptionCompare] Parameter Attribute

    So either of the following will also work (top option only available in VB , but both rely on VisualBasic.dll)

    Option Compare Text
    
    Replace("A","a","b")
    
    Replace("A","a","b", Compare := CompareMethod.Text)
    

提交回复
热议问题