Java Program to Remove Spaces from String

0
19

In this example, you learn about a Java program to remove spaces from a 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.


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 be featured and for contribution to codeamy.in and I also share java program soon.

Happy Coding!! 😊

Source

LEAVE A REPLY

Please enter your comment!
Please enter your name here