Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to trim the whitespace from a string? [duplicate]

Tags:

java

java-me

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.

/*
 * 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();
}
like image 356
user458442 Avatar asked Sep 26 '10 00:09

user458442


People also ask

How do I get rid of extra white spaces in a string?

The replaceAll() method of the String class replaces each substring of this string that matches the given regular expression with the given replacement. You can remove white spaces from a string by replacing " " with "".

How do I remove spaces between words in a string?

In Java, we can use regex \\s+ to match whitespace characters, and replaceAll("\\s+", " ") to replace them with a single space.


2 Answers

The simple way to trim leading and trailing whitespace is to call String.trim(). With Java 11 and later, you can also use String.strip() which uses a different interpretation of what "white space" means1.

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. if either count is non-zero, call String.substring(from, end) to create a new string containing the characters you want to keep.

This approach avoids copying any characters2.


1 - The different meanings are explained in the respective javadocs. Alternatively, read the answers to Difference between String trim() and strip() methods in Java 11.

2 - Actually, that depends on the implementation of String. For some implementations there will be no copying, for others a single copy is made. But either is an improvement on your approach, which entails a minimum of 2 copies, and more if there are any characters to trim.

like image 68
Stephen C Avatar answered Sep 30 '22 17:09

Stephen C


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

like image 45
Tony Ennis Avatar answered Sep 30 '22 18:09

Tony Ennis