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!
The trim() method will remove both leading and trailing whitespace from a string and return the result. The original string will remain unchanged. If there is no leading or trailing whitespace to be removed, the original string is returned. Both spaces and tab characters will be removed.
Method 1: Using ltrim() Method: The ltrim() method is used to strip whitespace only from the beginning of a string.
To remove leading and trailing spaces in Java, use the trim() method. This method returns a copy of this string with leading and trailing white space removed, or this string if it has no leading or trailing white space.
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);
As of JDK11
you can use stripLeading:
String result = temp.stripLeading();
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With