How do I remove white-space from the beginning of a string in Java without removing from the end?
If the value is:
String temp = " hi "
Then how can I delete only the leading white-space so it looks like this:
String temp = "hi "
The current implementation I have is to loop through, checking the first character and creating a substring until the first non-whitespace value is reached.
Thanks!
You could use:
temp = temp.replaceFirst("^\\s*", "")
You could use Commons-lang StringUtils stripStart method.
If you pass null it will automatically trim the spaces.
StringUtils.stripStart(temp, null);
Probably close to the implementation of the suggested Commons-lang StringUtils.stripStart() method:
public static String trimFront(String input) {
if (input == null) return input;
for (int i = 0; i < input.length(); i++) {
if (!Character.isWhitespace(input.charAt(i)))
return input.substring(i);
}
return "";
}
As of JDK11
you can use stripLeading:
String result = temp.stripLeading();
Blatantly copied from java2s:
text = text.replaceAll("^\\s+", "");
...and modified using @Reimus
's answer:
text = text.replaceFirst("^\\s+", "");
I'm not sure of the most efficient method; fwiw, I went with @Reimus
's original.