views:

57

answers:

4

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)

+4  A: 

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

musiKk
A: 

org.springframework.util.StringUtils.trimLeadingWhitespace(String)

Kai
The Javadocs say *"Miscellaneous string utility methods. Mainly for internal use within the framework; consider Jakarta's Commons Lang for a more comprehensive suite of string utilities."*
Stephen C
+4  A: 

You could do this in a regular expression:

"    foobar    ".replaceAll("^\\s+", "");
krock
It's funny how the one answer containing regex got accepted when it was stated that regex should be avoided. Personally I would use regex as well instead of a library--except that library is already part of the project.
musiKk
+1  A: 

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.

Kevin Bourrillion