Sunday, March 15, 2020

How to remove all the white-spaces in the String

What if we need to remove all the spaces exist in the string . The process of removing all the white spaces in the string is  called squeezing.
Squeezing is the combination of left trimming ,right trimming and the trimming of spaces that exist between the words.
How to remove all the white-spaces in the String

for example :
If the original string is : "    Alive is awesome   "
after squeezing
"Aliveisawesome"
Here  we are passing the string to the squeeze function ,there we traverse the string characters one by one.
if the character is not equal to the white space then it will print the character otherwise it will skip the character.
public class SqueezeString
{
    static int i;
   
    static void squeeze(String s)
    {
        for(i=0;i<s.length();i++)
        {
            char ch=s.charAt(i);
            if(ch != ' ')
            System.out.print(ch);
        }
    }
   
   
    public static void main (String args[])
    {
       
        System.out.println("Original String is : ");
        System.out.println("   manchester united is also known as red devil   ");
        SqueezeString.squeeze("   manchester united is also known as red devil    ");
    }
}

No comments:

Post a Comment