Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java equivalent of python's String lstrip()?

Tags:

java

string

trim

I'd like to remove the leading whitespace in a string, but without removing the trailing whitespace - so trim() won't work. In python I use lstrip(), but I'm not sure if there's an equivalent in Java.

As an example

"    foobar    "

should become

"foobar    "

I'd also like to avoid using Regex if at all possible.

Is there a built in function in Java, or do I have to go about creating my own method to do this? (and what's the shortest way I could achieve that)

like image 273
Iain Sproat Avatar asked Jun 23 '10 09:06

Iain Sproat


4 Answers

You could use the StringUtils class of Apache Commons Lang which has a stripStart() method (and many many more).

like image 52
musiKk Avatar answered Sep 22 '22 00:09

musiKk


You could do this in a regular expression:

"    foobar    ".replaceAll("^\\s+", "");
like image 26
krock Avatar answered Sep 22 '22 00:09

krock


Guava has CharMatcher.WHITESPACE.trimLeadingFrom(string). This by itself is not that different from other utility libraries' versions of the same thing, but once you're familiar with CharMatcher there is a tremendous breadth of text processing operations you'll know how to perform in a consistent, readable, performant manner.

like image 42
Kevin Bourrillion Avatar answered Sep 21 '22 00:09

Kevin Bourrillion


Since Java11 you can use .stripLeading() on a String to remove leading white-spaces and .stripTrailing() to remove trailing white-spaces.

The documentation for this can be found here: https://docs.oracle.com/en/java/javase/11/docs/api/java.base/java/lang/String.html#stripLeading()

Example:

String s = "    Hello there.    ";
s.stripLeading();    // "Hello there.    "
s.stripTrainling();  // "    Hello there."
s.strip();           // "Hello there."
like image 44
Biskit1943 Avatar answered Sep 20 '22 00:09

Biskit1943