Java Program to Remove Spaces from String

« Previous Program Next Program »

Remove Spaces from String

To remove/delete spaces from the string or sentence in Java programming, you have to ask to the user to enter the string. Now replace all the spaces from the string using the method replaceAll().

Java Programming Code to Remove Spaces from String

Following Java Program ask to the user to enter any sentence/string to remove all the spaces from the sentence/string, and then display the string/sentence after removing all the spaces:

/* Java Program Example - Remove Spaces from Sentence */
import java.util.Scanner;

public class JavaProgram
   public static void main(String args[])
        String str, strWithoutSpace;
        int i;
        Scanner scan = new Scanner(;
        System.out.print("Enter a Sentence : ");
        str = scan.nextLine();
        //1. Using replaceAll() Method
        strWithoutSpace = str.replaceAll(" ", "");
        //2. Without Using replaceAll() Method
        char[] strArray = str.toCharArray();
        StringBuffer sb = new StringBuffer();
        for (i = 0; i < strArray.length; i++)
            if( (strArray[i] != ' ') && (strArray[i] != '\t') )

When the above Java Program is compile and executed, it will produce the following output:

Java Program remove spaces from string

Same Program in Other Languages

You may also like to learn and practice the same program in other popular programming languages:

Java Online Test

« Previous Program Next Program »

© Copyright 2021. All Rights Reserved.