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

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

    My 2 cents:

    public static string Replace(this string originalString, string oldValue, string newValue, StringComparison comparisonType)
    {
        if (originalString == null)
            return null;
        if (oldValue == null)
            throw new ArgumentNullException("oldValue");
        if (oldValue == string.Empty)
            return originalString;
        if (newValue == null)
            throw new ArgumentNullException("newValue");
    
        const int indexNotFound = -1;
        int startIndex = 0, index = 0;
        while ((index = originalString.IndexOf(oldValue, startIndex, comparisonType)) != indexNotFound)
        {
            originalString = originalString.Substring(0, index) + newValue + originalString.Substring(index + oldValue.Length);
            startIndex = index + newValue.Length;
        }
    
        return originalString;
    }
    
    
    
    Replace("FOOBAR", "O", "za", StringComparison.OrdinalIgnoreCase);
    // "FzazaBAR"
    
    Replace("", "O", "za", StringComparison.OrdinalIgnoreCase);
    // ""
    
    Replace("FOO", "BAR", "", StringComparison.OrdinalIgnoreCase);
    // "FOO"
    
    Replace("FOO", "F", "", StringComparison.OrdinalIgnoreCase);
    // "OO"
    
    Replace("FOO", "", "BAR", StringComparison.OrdinalIgnoreCase);
    // "FOO"
    

提交回复
热议问题