Count number of words in the String with Example : Java Program Code

To find the number of words in the given String in java is easy . Here we are using arrays and string class to achieve our goal .

Read Also :   Count number of times each alphabet appears in the String

For example :

Original String : "Alive is awesome "    

If we pass the above string in the wordcount method then it will return

Output : 3          as the answer.

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


Read Also :   Find first non repeated character in the String with Example 



count number of words in string  java program code























Please find the code below :




public class StringDemo
{
    static int i,c=0,res;
    static int wordcount(String s)
    {
        char ch[]= new char[s.length()];      //in string especially we have to mention the () after length
        for(i=0;i<s.length();i++)
        {
            ch[i]= s.charAt(i);
            if( ((i>0)&&(ch[i]!=' ')&&(ch[i-1]==' ')) || ((ch[0]!=' ')&&(i==0)) )
            c++;
        }
        return c;
    }
    
    public static void main (String args[])
    {
        res=StringDemo.wordcount("   manchester united is also known as red devil ");
        //string is always passed in double quotes
        
        System.out.println("The number of words 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