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

前端 未结 9 1648
天涯浪人
天涯浪人 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:09

    I know of no canned instance in the framework, but here's another extension method version with a minimal amount of statements (although maybe not the fastest), for fun. More versions of replacement functions are posted at http://www.codeproject.com/KB/string/fastestcscaseinsstringrep.aspx and "Is there an alternative to string.Replace that is case-insensitive?" as well.

    public static string ReplaceIgnoreCase(this string alterableString, string oldValue, string newValue){
        if(alterableString == null) return null;
        for(
            int i = alterableString.IndexOf(oldValue, System.StringComparison.CurrentCultureIgnoreCase);
            i > -1;
            i = alterableString.IndexOf(oldValue, i+newValue.Length, System.StringComparison.CurrentCultureIgnoreCase)
        ) alterableString =
            alterableString.Substring(0, i)
            +newValue
            +alterableString.Substring(i+oldValue.Length)
        ;
        return alterableString;
    }
    

提交回复
热议问题