Here, we will write a program that asks for String input from the user and displays the string after eliminating or rather removing all the spaces.

The basic idea is to calculate the length, say N, of the input string and then run a Loop-construct that will iterate from 0 to (N-1).

At every iteration, it will extract the Ith character from the string and compare if its ASCII value is not 32 (ASCII value of ” “/ ‘ ‘/space: 32).

If the comparison is found to be true, accumulate the extracted character into a final String Variable. Display the result.

Code:

/* Program to enter a string and print it after removing all spaces.*/

import java.util.*;
class RemoveSpace
{
public static void main()
{
Scanner inp=new Scanner(System.in);
System.out.print("\n Enter String: ");
String s=inp.nextLine();
int k=s.length();
int i;
String z="";
char c;

for(i=0;i<k;i++)
{
c=s.charAt(i);
if(c!=32)
z=z+c;
}

System.out.println("String After Removing Spaces: "+z);

}
}

Output:

Enter String: Perks of Being a Wall Flower

String After Removing Spaces: PerksofBeingaWallFlower

Report Error/ Suggestion

Related Posts:

[yuzo_views]











CopyRight © 2019

CopyRight © 2019