Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Remove first white space in Java

Tags:

java

How would I remove the first white-space in Java?

Right now I am using this:

if (str.charAt(0) == ' ') str = str.replace(" ", "");
like image 358
mpluse Avatar asked Mar 21 '13 21:03

mpluse


2 Answers

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

like image 79
syb0rg Avatar answered Sep 29 '22 09:09

syb0rg


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.

like image 27
Keppil Avatar answered Sep 29 '22 09:09

Keppil