title: How do I remove a character from a String?
body: <pre><code>public static String removeChar(String s, char c) {
    StringBuffer r = new StringBuffer( s.length() );
    r.setLength( s.length() );
    int current = 0;
    for (int i = 0; i &lt; s.length(); i ++) {
       char cur = s.charAt(i);
       if (cur != c) r.setCharAt( current++, cur );
    }
    return r.toString();
  }
  </code></pre>
  
  <p>I've found the above code <a href="http://www.rgagnon.com/javadetails/java-0030.html" rel="nofollow">here</a>.</p>
  
  <p><strong>Two Questions:</strong></p>
  
  <ol>
  <li><p>why do we need to do setLength()? without which I am getting java.lang.StringIndexOutOfBoundsException: String index out of range: 0</p></li>
  <li><p>'ttr' and three junk chars are coming when I run this program with parameters - "teeter" and "e". How to remove the unused whitespaces in the buffer?</p></li>
  </ol>