Remove first white space in Java

Just use str.trim() to get rid of all leading and trailing spaces.


Use replaceFirst() instead of replace().

TO get rid of all leading spaces you can use

str = str.replaceFirst("^ *", "");

The ^ is just to make sure that the spaces are actually at the start of the string, which it seems like you wanted. If that is not the case, just remove it.


You can use trim()

newString = stringToTrim.trim();

That will trim both sides of the string... beginning and end.. not sure if that helps.

More info here... http://docs.oracle.com/javase/7/docs/api/

Tags:

Java