English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية
In this program, you will learn to use regular expressions in Java to remove all spaces from a given string.
public class Whitespaces { public static void main(String[] args) { String sentence = "T his is b ett er! www. w"3codebox. com"; System.out.println("Original sentence: ", + sentence); sentence = sentence.replaceAll("\\s", ""); System.out.println("After replacing and deleting spaces: ", + sentence); } }
When running the program, the output is:
Original sentence: This is better!www. w3codebox. com After replacing and deleting spaces: Thisisbetter!www.oldtoolbag.com
In the above program, we use the String's replaceAll() method to delete and replace all spaces in the string sentence.
We use the regular expression \\s to find all whitespace characters (tab, space, newline, etc.) in the string. Then, we replace it with an empty string.