59

What is a good alternative of JavaScript ltrim() and rtrim() functions in Java?

rene
  • 41,474
  • 78
  • 114
  • 152
yegor256
  • 102,010
  • 123
  • 446
  • 597

7 Answers7

62

With a regex you could write:

String s = ...
String ltrim = s.replaceAll("^\\s+","");
String rtrim = s.replaceAll("\\s+$","");

If you have to do it often, you can create and compile a pattern for better performance:

private final static Pattern LTRIM = Pattern.compile("^\\s+");

public static String ltrim(String s) {
    return LTRIM.matcher(s).replaceAll("");
}

From a performance perspective, a quick micro benchmark shows (post JIT compilation) that the regex approach is about 5 times slower than the loop (0.49s vs. 0.11s for 1 million ltrim).

I personally find the regex approach more readable and less error prone but if performance is an issue you should use the loop solution.

assylias
  • 321,522
  • 82
  • 660
  • 783
34

Using regex may be nice, but it's quite a lot slower than a simple trimming functions:

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

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

Also, there are some libraries providing such functions. For example, Spring StringUtils. Apache Commons StringUtils provides similar functions too: strip, stripStart, stripEnd

StringUtils.stripEnd("abc  ", null)    = "abc"
bezmax
  • 25,562
  • 10
  • 53
  • 84
  • 4
    +1. I would not call this "trim" though, because String#trim does not trim whitespace, it trims control characters and some ASCII-only whitespace. Commons Lang calls their version (which does what you do and what everyone probably wants) "strip". – Thilo Mar 22 '13 at 09:50
  • Another +1 if I could for the link to StringUtils in Spring, which has "trimLeadingWhitespace". – Thilo Mar 22 '13 at 09:53
  • 1
    Yes, @Thilo is right. To make it work like original java trim function, just change the conditional to `s.charAt(i) <= ' '`. – bezmax Mar 22 '13 at 09:54
  • 1
    But don't do that. That original trim spec seems just weird. – Thilo Mar 22 '13 at 09:56
  • Shouldn't that be `while(i >= 0 ...`? Otherwise, `rtrim( " ")` returns a single space character. – nickb Apr 12 '13 at 18:16
11
import org.apache.commons.lang3.StringUtils;

private String rTrim(String str) {
    return StringUtils.stripEnd(str, /*stripChars*/" ");
}

private String lTrim(String str) {
    return StringUtils.stripStart(str, /*stripChars*/" ");
}
YAA
  • 409
  • 1
  • 5
  • 11
7

You can simply try the following

String s = "  Hello world  "

String ltrim = s.stripLeading();

String rtrim = s.stripTrailing();
Umutambyi Gad
  • 4,082
  • 3
  • 18
  • 39
user3601193
  • 97
  • 2
  • 3
  • Good answer. This has been available since Java 11. No need anymore for custom code, or external libraries. – John Nov 02 '20 at 18:30
3

Guava has CharMatcher trimLeadingFrom and trimTrailingFrom

e.g. CharMatcher.whitespace.trimTrailingFrom(s)

Andrew McKinlay
  • 2,431
  • 1
  • 24
  • 27
2

Based on the answer of @bezmax I had a look at the Spring StringUtils, but it couldn't justify the overload for me of switching to the Spring framework. Therfore I decided to create a Characters class to easily left / right trim strings for any given character(-class). The class is available on GitHub.

Characters.valueOf('x').trim( ... )
Characters.valueOf('x').leftTrim( ... )
Characters.valueOf('x').rightTrim( ... )

If you would like to trim for whitespaces, there is a predefined character-class available:

Characters.WHITESPACE.trim( ... )
Characters.WHITESPACE.leftTrim( ... )
Characters.WHITESPACE.rightTrim( ... )

The class does feature also other kinds of character operations, such condense, replace or split.

Kristian Kraljic
  • 826
  • 12
  • 11
2

Might be a bit cheap, but you might also use these without any other library:

final var string = "   Hello World   ";

final var rtrimmed = ("." + string).trim().substring(1);
// => "   Hello World"

var ltrimmed = (string + ".").trim();
ltrimmed = ltrimmed.substring(0, ltrimmed.length - 1);
// => "Hello World   "

I admit, that the ltrimmed is not that pretty, but it will do the trick.

Tharabas
  • 3,402
  • 1
  • 30
  • 29
  • Nice idea! Looks odd, but might well be the shortest way, syntactically. I use it in Elasticsearch Painless (Java-based) scripting where regexp is disabled by default. – mgaert Jan 16 '23 at 17:11