tags:

views:

88

answers:

4

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 java.lang.ArrayIndexOutOfBoundsException on this. So, apparently either it doesn't like the way i've initialized the newChars array, or i'm not doing something correctly when calling System.arraycopy(). Any and all advice is appreciated!

/*
 * remove any leading and trailing spaces
 */
public static String trim(String str) {
    char[] chars = str.toCharArray();
    int len = chars.length;
    // leading
    while ( (len > 0 ) && ( 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();
}
+1  A: 

String.trim() is very old, at least to java 1.3. You don't have this?

Tony Ennis
Actually, yes - I somehow missed it when looking for the solution. :/ Many thanks.
Yay! Easy fix!!!
Tony Ennis
+2  A: 

The simple way to trim leading and trailing whitespace is to call String.trim(). If you just want to trim just leading and trailing spaces (rather than all leading and trailing whitespace), there is an Apache commons method called StringUtils.strip(String, String) that can do this; call it with " " as the 2nd argument.

Your attempted code has a number of bugs, and is fundamentally inefficient. If you really want to implement this yourself, then you should:

  1. count the leading space characters
  2. count the trailing space characters
  3. call String.substring(from, end) to create a new string containing the characters you want to keep.

This approach avoids copying any characters.

Stephen C
A: 

The destination array newChars is not large enough to hold the values copied. You need to initialize it to the length of the data you intend to copy (so, length - 1).

Fredrick Pennachi
A: 

First of all, what others said about String.trim(). Really, don't reinvent the wheel.

But for the record, what's going wrong with your code is that Java arrays aren't resizeable. When you initially set up your target array, you create it as a size 0 array. You then tell System.arraycopy to stuff len - 1 characters in there. That's not going to work. If you wanted it to work, you'd need to set up the array as:

char[] newChars = new char[len - 1];

But that's amazingly inefficient, reallocating and copying a new array each time through the loop. Use the three steps that Stephen C mentioned, ending with a substring.

Daniel Martin