替换不区分大小写的 StringBuilder

Replace Case Insensitive StringBuilder

我已经多次阅读关于在需要多次替换时使用 Stringbuilder 与 string 的优点。我需要将 HTML 字符串(所有格式都非常简单)转换为 WIKI 表示法,并打算从我在 SO 上找到的代码中自己滚动。我想知道是否有更简单的方法来执行此操作,以及如何使用它来实现 StringBuilder 的好处。到目前为止,我所有的尝试都惨遭失败。请提前告知并谢谢。

    public static string ConvertHTML2WIKInotation(string htmlstring)
        {
            StringBuilder sb = new StringBuilder(htmlstring);

            htmlstring = ReplaceInsensitive(htmlstring, "<hr>", "----");
            htmlstring = ReplaceInsensitive(htmlstring, "<hr />", "----");
            ... etc.

            return sb.ToString();
        }

        static public string ReplaceInsensitive(this string str, string from, string to)
        {
            str = Regex.Replace(str, from, to, RegexOptions.IgnoreCase);
            return str;
        }

stringbuilder 的好处是您不必在每次替换时都创建一个新字符串。您的实施不会从中受益 属性。 如果您使用 stringbuilder,实际上是在 stringbuilder 上进行转换,而不是在输入字符串参数上:

    public static string ConvertHTML2WIKInotation(string htmlstring)
    {
        StringBuilder sb = new StringBuilder(htmlstring);

        sb.Replace("<hr>", "----");
        sb.Replace("<hr />", "----");

        return sb.ToString();
    }

如果需要不区分大小写,请看: How to do a multiple case insensitive replace using a StringBuilder

由于 html 标签不区分大小写,我建议不要使用 StringBuilder,因为不建议将 SB 用于需要更多替换字符串的场景。

public static string ReplaceMultiple(
          string template, 
          IEnumerable<KeyValuePair<string, string>> replaceParameters)
{
   var result = template;

   foreach(var replace in replaceParameters)
   {
      var templateSplit = Regex.Split(result, 
                                    replace.Key, 
                                    RegexOptions.IgnoreCase);
      result = string.Join(replace.Value, templateSplit);
   }

   return result;
}