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.
The above solution is the algorithm with the complexity of O(n) without using any java function.
My method before I found the second answer using regex as a better solution. Maybe someone needs this code.
Try this:
See also
String.trim()
No
trim()
regexIt's also possible to do this with just one
replaceAll
, but this is much less readable than thetrim()
solution. Nonetheless, it's provided here just to show what regex can do:There are 3 alternates:
^_+
: any sequence of spaces at the beginning of the string$1
, which captures the empty string_+$
: any sequence of spaces at the end of the string$1
, which captures the empty string(_)+
: any sequence of spaces that matches none of the above, meaning it's in the middle$1
, which captures a single spaceSee also
Try this one.
Sample Code
OUTPUT
First it will replace all the spaces with single space. Than we have to supposed to do trim
String
because Starting of theString
and End of theString
it will replace the all space with single space ifString
has spaces at Starting of theString
and End of theString
So we need to trim them. Than you get your desiredString
.check this...
If String contains only single-space then replace() will not-replace,
If spaces are more than one, Then replace() action performs and removes spacess.
To count the number of spaces in a String.
Pattern.quote("?") returns literal pattern String.
See
String.replaceAll
.Use the regex
"\s"
and replace with" "
.Then use
String.trim
.