Alex Rivera | Logout

Java how to replace 2 or more spaces with single space in string and delete leading and trailing spaces

Asked 2010-05-28T20:43:11.853
353

Looking for quick, simple way in Java to change this string

" hello     there   "

to something that looks like this

"hello there"

where I replace all those multiple spaces with a single space, except I also want the one or more spaces at the beginning of string to be gone.

Something like this gets me partly there

String mytext = " hello     there   ";
mytext = mytext.replaceAll("( )+", " ");

but not quite.

Edit
Report

1 Answer

12

You can first use String.trim(), and then apply the regex replace command on the result.

answered 2010-05-28T20:46:28.023

Your Answer