Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I remove white-space from the beginning of a string?

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!

like image 737
sailboatlie Avatar asked Oct 05 '12 21:10

sailboatlie


People also ask

How do you remove the white space at the beginning of a string?

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.

Which function is used to remove whitespace from beginning of the string?

Method 1: Using ltrim() Method: The ltrim() method is used to strip whitespace only from the beginning of a string.

How do I remove the white space at the beginning of a string in Java?

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.


3 Answers

You could use:

temp = temp.replaceFirst("^\\s*", "")
like image 63
Reimeus Avatar answered Nov 08 '22 10:11

Reimeus


You could use Commons-lang StringUtils stripStart method.

If you pass null it will automatically trim the spaces.

StringUtils.stripStart(temp, null);
like image 40
JustinKSU Avatar answered Nov 08 '22 10:11

JustinKSU


As of JDK11 you can use stripLeading:

String result = temp.stripLeading();
like image 22
Ousmane D. Avatar answered Nov 08 '22 10:11

Ousmane D.