title: Replacing bad characters of a String with bad characters
body: <p>I just wondered what's the easiest way to replace a string characters that must be replaced subsequently. </p>
  
  <p>For example:</p>
  
  <pre><code>var str = "[Hello World]";
  //enclose all occurences of [ and ] with brackets[] 
  str = str.Replace("[","[[]").Replace("]","[]]");
  </code></pre>
  
  <ul>
  <li>The desired result: <code>[[]Hello World[]]</code></li>
  <li>The actual result: <code>[[[]]Hello World[]]</code></li>
  </ul>
  
  <p>The reason is obviously the second replace on the already modified string.</p>
  
  <p>So how to replace all occurences of "bad" characters with characters that contain "bad" characters?</p>
  
  <hr>
  
  <p>A quick measurement of all approaches revealed that the <a href="https://stackoverflow.com/a/9264450/284240">StringBuilder</a> is the most efficient way.</p>
  
  <p>190kb file (all in  milliseconds)</p>
  
  <blockquote>
  <pre><code>  regexTime           40.5065  
    replaceTime         20.8891  
    stringBuilderTime    6.9776
  </code></pre>
  </blockquote>
  
  <p>7MB file</p>
  
  <blockquote>
  <pre><code>  regexTime           1209.3529           
    replaceTime          403.3985   
    stringBuilderTime    175.2583
  </code></pre>
  </blockquote>
  
  <p>By the way, the direct <code>StringBuilder</code> approach from <em>John</em>  was twice as fast as the <a href="http://msdn.microsoft.com/en-us/library/bb548651.aspx" rel="nofollow noreferrer">Aggregate</a> approach from <em>Sehe</em>.</p>
  
  <p>I've made an extension out of it:</p>
  
  <pre><code>public static String EncloseChars(this string input, char[] charsToEnclose, String leftSide, String rightSide) {
      if (charsToEnclose == null || leftSide == null || rightSide == null)
          throw new ArgumentException("Invalid arguments for EncloseChars", charsToEnclose == null ? "charsToEnclose" : leftSide == null ? "leftSide" : "rightSide");
      Array.Sort(charsToEnclose);
      StringBuilder sb = new StringBuilder();
      foreach (char c in input) {
          if (Array.BinarySearch(charsToEnclose, c) &gt; -1)
              sb.Append(leftSide).Append(c).Append(rightSide);
          else 
              sb.Append(c);
      }
      return sb.ToString();
  }
  
  "[Hello World]".EncloseChars(new char[]{'[', ']'},"[","]");
  </code></pre>