Regex to remove spaces

java, regex

Solution

The following will do it:

str = str.replaceAll(" ", "");

Alternatively:

str = str.replaceAll(" +", "");

In my benchmarks, the latter was ~40% faster than the former.

Problem

How to write a regex to remove spaces in Java? For example ``` Input : " " Output : "" --------------------- Input : " " Output : "" ``` Note that tabs and new lines should not be removed. Only spaces should be removed. Edit : How do we make a check ? For example how to check in an if statement that a String contains only spaces (any number of them) ``` if(<statement>) { //inside statement } ``` For ``` input = " " or input = " " ``` The control should should go inside if statement.

Original source