Iain Sproat
Iain Sproat

Reputation: 5340

Java equivalent of python's String lstrip()?

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)

Upvotes: 6

Views: 4277

Answers (5)

Koschi13
Koschi13

Reputation: 619

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."

Upvotes: 2

Kevin Bourrillion
Kevin Bourrillion

Reputation: 40851

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.

Upvotes: 2

krock
krock

Reputation: 29629

You could do this in a regular expression:

"    foobar    ".replaceAll("^\\s+", "");

Upvotes: 5

musiKk
musiKk

Reputation: 15189

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

Upvotes: 10

Related Questions