Java Program to Remove All the blank Spaces in String

In this tutorial, we are going to learn java program to remove all the blank spaces between the input string by the user.

For any input string, we have to check for the blank space and then remove it.

For Example

Case1: If the user input the string ‘Que scol’,

          The output should be ‘Quescol’.

Case2: If the user input the string ‘Jav a Pro gram’,

          The output should be ‘JavanProgram’.

Java Program to Remove All the blank Spaces in String

import java.util.*;
public class Main
{
    public static void main (String[]args){
        System.out.println("Java program to remove blank space from string ");
        Scanner sc = new Scanner (System.in);
        System.out.println ("Please enter a String");
        String str = sc.nextLine(); 
        StringBuilder tempStr = new StringBuilder();
        for(int i = 0; i < str.length(); i++){
            if(!(str.charAt(i)== ' ')) {        
                    tempStr.append(str.charAt(i));
            } 
        }
        System.out.println("String After removing space");
        System.out.println (tempStr);
    }
}

Output

Java program to remove blank space from string 
Please enter a String
I am quescol
String After removing space
Iamquescol

Explanation

In this case, the input string is ‘Jav a pro gra m’, which consists of 5 spaces in the string. During the iteration of the string, when these spaces are found then the ‘if’ statement executes that skips the spaces and concatenate the remaining character in the empty string ‘tempStr’ and finally print the ‘tempStr’ as the output of the program, in this case, the output is ‘Javaprogram’.