Count number of White Spaces in the String : Java Program Code

In this program we will calculate the number of spaces or white spaces in the string .
For example , if the string is
"Alive is awesome"
then the answer is 2 .

This is quite useful when some one takes the input from the user such as first name , last name or any other input in string format .

Here we are passing String to the spacecount() function which return the int value that is the number of white spaces  in the string .



white spaces count in the string java program code



















Please find the code below :




public class SpaceCount
{
    
    static int i,c=0,res;
    
    
    static int spacecount(String s)
    {
        for(i=0,c=0;i<s.length();i++)
        {
            char ch=s.charAt(i);
            if(ch==' ')
            c++;
        }
        return c;
    }
    
    public static void main (String args[])
    {
        res=SpaceCount.spacecount("i am adult ");
        //string is always passed in double quotes
        
        System.out.println("The number of white spaces  in the String are :  "+res);
    }
}

About The Author

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