English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية

Java Basic Tutorial

Java Flow Control

Java Arrays

Java Object-Oriented (I)

Java Object-Oriented (II)

Java Object-Oriented (III)

Java Exception Handling

Java List

Java Queue (Queue)

Java Map Collection

Java Set Collection

Java Input/Output (I/O)/O)

Java Reader/Writer

Other Java Topics

Java program to remove all spaces from a string

Comprehensive Java Examples

In this program, you will learn to use regular expressions in Java to remove all spaces from a given string.

Example: Program to remove all spaces

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.

Comprehensive Java Examples