Java : Remove or Removing all the Whitespaces ( Blank 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.
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.





Demo : 



squeeze whitespaces in the string java program code






















Please find the code below :



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    ");
    }
}

About The Author

Subham Mittal has worked in Oracle for 3 years.
Enjoyed this post? Never miss out on future posts by subscribing JavaHungry