Java Program to Remove Spaces from String

In this example, You learn about Java program to remove spaces from string. 

Here you learn Java remove spaces from string, You are given a string and the task of the program to remove spaces in Java.

We use length() function to find a length of string and charAt() to find character at specific index. 


java remove spaces from string


To remove space we create new empty string and append each character from original string to this new string if find space ' ' then skip it to append (as space is treated as character). Then print the new string.

Java Program to Remove Spaces from String


import java.util.*;

public class Main{
  
    public static void main(String[] args) {
        Scanner scn = new Scanner(System.in);
        String S;
        S = scn.nextLine();
        String str = "";
        for(int i=0; i<S.length(); i++){
            if(S.charAt(i) != ' '){
                str = str+S.charAt(i);
            }
        }
        System.out.println(str);
    }
}

Output


 Codeamy . in
 Codeamy.in


In the above article, I shared Java Remove Spaces from String. If you know something new then please comment or send mail to featured and for contribution to codeamy.in and I also share java program soon.


Happy Coding!! 😊

If you have any doubts, Please let me know

Previous Post Next Post

Contact Form