title: How to trim the whitespace from a string?
body: <p>I am writing this function for a J2ME application, so I don't have some of the more advanced / modern Java classes available to me. I am getting <code>java.lang.ArrayIndexOutOfBoundsException</code> on this. So, apparently either it doesn't like the way I've initialized the <code>newChars</code> array, or I'm not doing something correctly when calling <code>System.arraycopy</code>.</p>
  
  <pre><code>/*
   * remove any leading and trailing spaces
   */
  public static String trim(String str) {
      char[] chars = str.toCharArray();
      int len = chars.length;
      // leading
      while ( (len &gt; 0 ) &amp;&amp; ( chars[0] == ' ' ) ) {
          char[] newChars = new char[] {}; // initialize empty array
          System.arraycopy(chars, 1, newChars, 0, len - 1);
          chars = newChars;
          len = chars.length;
      }
      // TODO: trailing
      return chars.toString();
  }
  </code></pre>