String.Replace ignoring case

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

    Lots of suggestions using Regex. How about this extension method without it:

    public static string Replace(this string str, string old, string @new, StringComparison comparison)
    {
        @new = @new ?? "";
        if (string.IsNullOrEmpty(str) || string.IsNullOrEmpty(old) || old.Equals(@new, comparison))
            return str;
        int foundAt = 0;
        while ((foundAt = str.IndexOf(old, foundAt, comparison)) != -1)
        {
            str = str.Remove(foundAt, old.Length).Insert(foundAt, @new);
            foundAt += @new.Length;
        }
        return str;
    }
    

提交回复
热议问题