12

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

1
  • do you want to remove all whitespace or only leading and trailing whitespaces? Commented Sep 27, 2012 at 16:15

1 Answer 1

23

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.

Example:

String str = ' how is   the weather today ';

str = str.trim();

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

return str;

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .