2

I have read many times over about the virtue of using Stringbuilder vs. string when multiple replacements are needed. I need to convert an HTML string (all very simple formatting) to WIKI notation and was going to roll my own from code I found on SO. I'm wondering if there is a simpler way to do this, and also how I can implement the benefits of a StringBuilder with it. All my attempts til now have failed miserably. Please advise and thank you in advance.

    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;
        }
lng
  • 805
  • 1
  • 11
  • 31
Darkloki
  • 676
  • 1
  • 13
  • 31

2 Answers2

1

Since html tags case insensitive, I would suggest non StringBuilder since SB is not recommended for the scenarios where you need more replace string.

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;
}
RAJA.P.N
  • 106
  • 8
  • I'm sorry, I'm not well versed on IEnumerables, how do you go about creating the replaceParameters parameter? – Darkloki Sep 14 '16 at 18:07
  • Try this: replaceParameters = new [] { new KeyValuePair("
    ","----"), new KeyValuePair("
    ","----") };
    – RAJA.P.N Sep 14 '16 at 18:11
0

The benefit of stringbuilder is that you don't create a new string with every replacement. Your implementation doesn't benefit from this property. If you use a stringbuilder, actually do transformations on the stringbuilder, not on the input string parameter:

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

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

        return sb.ToString();
    }

If it needs to be case insensitive, look at: How to do a multiple case insensitive replace using a StringBuilder

Community
  • 1
  • 1
Norbert Huurnink
  • 1,326
  • 10
  • 18