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

16

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

How do I do this?

For the time being I'm traversing the string with a loop and removing all the blanks from the beginning (until it reaches a character) or the end (making a loop to the beginning of string ).

    
asked by anonymous 04.02.2014 / 18:55

4 answers

11

You can use regex:

Right Trim:

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

Left Trim:

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

Source: link

    
04.02.2014 / 18:59
8

Source: link

    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);
    }
    
04.02.2014 / 18:59
5
The Apache Commons library has methods in the StringUtils class that can remove miscellaneous characters from the beginning or end of a string:

Left:

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

Right:

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

I did not find a match in Guava . :

Anyway, with regex you do this on a line only and without additional libraries (see Maicon's answer).

    
04.02.2014 / 19:24
3

Solutions based on regex are particularly slow and have poor performance for this problem. The reason is that they have been 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 String.trim() method, which in OpenJDK 8 looks like this:

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;
}

Notice the two while loops. The first loop is jumping the spaces of the beginning, while the second is discounting the spaces of the end. Therefore, it is possible to create a version of rtrim() and 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 place these methods in another helper class, since it is not possible to add them directly to the String class.
  • Simplify the resulting code. Since each of the resulting methods will only do% s of one side, 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 was on both sides.

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 test running on Ideone .

    
24.08.2016 / 17:54