String.Replace ignoring case

前端 未结 17 803
野趣味
野趣味 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:54

    Using @Georgy Batalov solution I had a problem when using the following example

    string original = "blah,DC=bleh,DC=blih,DC=bloh,DC=com"; string replaced = original.ReplaceIgnoreCase(",DC=", ".")

    Below is how I rewrote his extension

    public static string ReplaceIgnoreCase(this string source, string oldVale, 
    string newVale)
        {
            if (source.IsNullOrEmpty() || oldVale.IsNullOrEmpty())
                return source;
    
            var stringBuilder = new StringBuilder();
            string result = source;
    
            int index = result.IndexOf(oldVale, StringComparison.InvariantCultureIgnoreCase);
            bool initialRun = true;
    
            while (index >= 0)
            {
                string substr = result.Substring(0, index);
                substr = substr + newVale;
                result = result.Remove(0, index);
                result = result.Remove(0, oldVale.Length);
    
                stringBuilder.Append(substr);
    
                index = result.IndexOf(oldVale, StringComparison.InvariantCultureIgnoreCase);
            }
    
            if (result.Length > 0)
            {
                stringBuilder.Append(result);
            }
    
            return stringBuilder.ToString();
        }
    

提交回复
热议问题