code: public static String trimWhitespace(String s) {
      StringBuilder filter = new StringBuilder();
      String str = s.trim();
      for (int i = 0; i < str.length(); i++) {
        while (str.charAt(i) <= ' ' && i < str.length() &&
            (str.charAt(i + 1) <= ' ' || i > 1 && str.charAt(i - 1) <= ' ')) {
          i++;
        }
        char c = str.charAt(i);
        if (c != '\n' && c != '\t' && c != '\r') {
          filter.append(c);
        }
      }
      return filter.toString();
    }
docs: Filters any whitespace characters. Useful for trimming the contents of
  token elements that cannot possibly contain any spaces, with the exception
  for a single space in a word (for example, if the language supports numbers
  formatted with spaces as single tokens, as Catalan in LanguageTool).
  
  @param s String to be filtered.
  @return Filtered s.