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 charactercharacters i.e. /(\s+\\s+)/
and replaces itthem with a single space.
Example:
String str = ' how is the weather today ';
str = str.trim();
str = str.replaceAll('(\\s+)', ' ');
return str;