Skip to Content
Java Coding Problems
book

Java Coding Problems

by Anghel Leonard
September 2019
Intermediate to advanced
816 pages
18h 47m
English
Packt Publishing
Content preview from Java Coding Problems

8. Removing white spaces from a string

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 \t, \n, and \r:

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().
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Start your free trial

You might also like

Java Coding Problems - Second Edition

Java Coding Problems - Second Edition

Anghel Leonard
Java in a Nutshell, 7th Edition

Java in a Nutshell, 7th Edition

Benjamin J. Evans, David Flanagan
The Well-Grounded Java Developer, Second Edition

The Well-Grounded Java Developer, Second Edition

Benjamin Evans, Martijn Verburg, Jason Clark

Publisher Resources

ISBN: 9781789801415Supplemental Content