The solution to this problem consists of using the String.replaceAll() method with the s regular expression. Mainly, s removes all white spaces, including the non-visible ones, such as , , and :
public static String removeWhitespaces(String str) {
return str.replaceAll("\s", "");
}
Starting with JDK 11, String.isBlank() checks whether the string is empty or contains only white space code points. For third-party library support, please consider Apache Commons Lang, StringUtils.deleteWhitespace(), and the Spring Framework, StringUtils.trimAllWhitespace().