String.Replace ignoring case

前端 未结 17 804
野趣味
野趣味 2020-11-29 19:03

I have a string called \"hello world\"

I need to replace the word \"world\" to \"csharp\"

for this I use:

string.Replace(\"World\", \"csharp\         


        
17条回答
  •  醉话见心
    2020-11-29 19:51

    Modified @Darky711's answer to use the passed in comparison type and match the framework replace naming and xml comments as closely as possible.

    /// 
    /// Returns a new string in which all occurrences of a specified string in the current instance are replaced with another specified string.
    /// 
    /// The string performing the replace method.
    /// The string to be replaced.
    /// The string replace all occurrances of oldValue.
    /// Type of the comparison.
    /// 
    public static string Replace(this string str, string oldValue, string @newValue, StringComparison comparisonType)
    {
        @newValue = @newValue ?? string.Empty;
        if (string.IsNullOrEmpty(str) || string.IsNullOrEmpty(oldValue) || oldValue.Equals(@newValue, comparisonType))
        {
            return str;
        }
        int foundAt;
        while ((foundAt = str.IndexOf(oldValue, 0, comparisonType)) != -1)
        {
            str = str.Remove(foundAt, oldValue.Length).Insert(foundAt, @newValue);
        }
        return str;
    }
    

提交回复
热议问题