Java Program to Delete All Space Characters from a String

Here is a Java program to remove all space characters from a string using replaceAll() method. In this java program, we have to delete all occurrences of space characters from a given string and then print it on screen.

For Example,
Input String : Tech Crash Course
Output String : TechCrashCourse

Java program to remove all spaces from string using replaceAll method

In this java program, we will first take a string as input from user and store it in a String object "str". To delete all space characters from str, we will call replaceAll() method of String class. This method replaces any occurrence of space characters(including multiple adjacent space characters) with "". We are using "[ ]" regular expression, which matches with any space character.

package com.tcc.java.programs;

import java.util.Scanner;

public class DeleteSpaces {
    public static void main(String args[]) {
        String str, output;
        Scanner scanner = new Scanner(System.in);

        System.out.println("Enter a String");
        str = scanner.nextLine();

        output = str.replaceAll("[ ]", "");

        System.out.println("Output String\n" + output);
    }
}
Output
Enter a String
I love  Java  Programming
Output String
IloveJavaProgramming
Enter a String
Java Programm     to remove spaces
Output String
JavaProgrammtoremovespaces

Recommended Posts
Java Program to Delete all Vowel Characters from String
Java Program to Delete a Word from Sentence
Java Program to Reverse Sequence of Words of a Sentence
Java Program to Find Length of a String
Java Program to Copy a String
Java Program to Reverse a String
Java Program to Concatenate Two Strings
Java Program to Check Two Strings are Anagram or Not
Java Program to Find Count of Each Character in a String
Java Program to generate a sequence of random numbers
Java Program to Check Whether a Number is Armstrong Number or Not
All Java Programs