How to remove spaces in between the String

Use \\s+ instead of \\s as there are two or more consecutive whitespaces in your input.

string = str.replaceAll("\\s+"," ")

You can use replaceAll which takes a regex as parameter. And it seems like you want to replace multiple spaces with a single space. You can do it like this:

string = str.replaceAll("\\s{2,}"," ");

It will replace 2 or more consecutive whitespaces with a single whitespace.


First get rid of multiple spaces:

String after = before.trim().replaceAll(" +", " ");