How do LTRIM() and RTRIM() in Java?

Asked

Viewed 8,554 times

17

I need to process some strings in Java. I know the method exists trim(), but I need a Left Trim and of a Right Trim.

How do I do this?

For now I’m walking the string with a loop and removing all whitespace from the beginning (until it reaches a character) or the end (making a loop from the end to the beginning of string).

4 answers

13


You can use regex:

Right Trim:

String texto_filtrado = original.replaceAll("\\s+$", "");

Left Trim:

String texto_filtrado = original.replaceAll("^\\s+", "");

Source: http://www.xinotes.org/notes/note/1418/

  • 3

    This guy Regex seems to know the answer to everything, awesome.

  • Regexlife saver =D

  • 1

    "What a Regex and silver tape not solve, nothing else will solve."

9

Source: http://www.fromdev.com/2009/07/playing-with-java-string-trim-basics.html

    public static String ltrim(String s) {
        int i = 0;
        while (i < s.length() && Character.isWhitespace(s.charAt(i))) {
            i++;
        }
        return s.substring(i);
    }

    public static String rtrim(String s) {
       int i = s.length()-1;
       while (i > 0 && Character.isWhitespace(s.charAt(i))) {
            i--;
       }
       return s.substring(0,i+1);
    }

6

The library Apache Commons has methods in class StringUtils that can remove several characters from the beginning or end of a string:

On the left:

String semEspacosOuTabulacosAEsquerda = StringUtils.stripStart(original, " \t");

On the right:

String semEspacosOuTabulacoesADireita = StringUtils.stripEnd(original, " \t");

I didn’t find a match in Guava. :(

Anyway, with regex you do it in one line and no additional libraries (see Maicon’s reply).

4

Regex-based solutions are particularly slow and perform poorly for this problem. The reason is that they were designed for significantly more complicated and complex problems than this, and you end up using a cannon to kill an ant.

To design the ideal solution in terms of performance, nothing better than looking at the source code of the method String.trim(), that in Openjdk 8 that’s how it is:

public String trim() {
    int len = value.length;
    int st = 0;
    char[] val = value;    /* avoid getfield opcode */

    while ((st < len) && (val[st] <= ' ')) {
        st++;
    }
    while ((st < len) && (val[len - 1] <= ' ')) {
        len--;
    }
    return ((st > 0) || (len < value.length)) ? substring(st, len) : this;
}

Observe the two loops while. The first loop is skipping the spaces of the beginning, while the second loop is discounting the spaces of the end. It is therefore possible to create a version of rtrim() and of ltrim() by doing the following:

  • Implement two distant versions of this method above, taking a loop from one of them and the other loop from the other.
  • Make the necessary modifications to put these methods in another auxiliary class, since it is not possible to add them directly to the class String.
  • Simplify the resulting code. Once each of the resulting methods will do the trim only on the one hand, it is possible to simplify or remove some expressions that would be constant, or always true or always false that would only be important if the trim either way.

Here is the resulting code:

public static String rtrim(String toTrim) {
    char[] val = toTrim.toCharArray();
    int len = val.length;

    while (len > 0 && val[len - 1] <= ' ') {
        len--;
    }
    return len < val.length ? toTrim.substring(0, len) : toTrim;
}

public static String ltrim(String toTrim) {
    int st = 0;
    char[] val = toTrim.toCharArray();
    int len = val.length;

    while (st < len && val[st] <= ' ') {
        st++;
    }
    return st > 0 ? toTrim.substring(st, len) : toTrim;
}

See here a working test on Ideone.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.