This is an extension of my earlier question where i was using normalizeSpace(). But since this available only from api 26. How do we remove the whitespaces for earlier versions

  • do you want to remove all whitespace or only leading and trailing whitespaces? – Andree Wille Sep 27 '12 at 16:15

If going back to basics I would suggest using the trim() function followed by a regex replacement using replaceAll() that matches instances of the space characters i.e. (\\s+) and replaces them with a single space.


String str = ' how is   the weather today ';

str = str.trim();

str = str.replaceAll('(\\s+)', ' ');

return str;

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.