Count the number of words in a string - Java

Q. Write a program to count the number of words in given string.

Answer:

The words are separated by space in the given sentence. In this example, split the string at each space and count them. The charAt() method is used to return the character located at the String's specified index. 

WordCount.java

class WordCount
{
    static int i,count=0,result;
    static int wordcount(String str)
    {
        char ch[]= new char[str.length()];     
        for(i=0; i<str.length(); i++)
        {
            ch[i] = str.charAt(i);
            if( ((i>0)&&(ch[i]!=' ')&&(ch[i-1]==' ')) || ((ch[0]!=' ')&&(i==0)) )
            count++;
        }
        return count;
    }    
    public static void main (String args[])
    {
        result = WordCount.wordcount("Java is a pure Object oriented programming language ");
        System.out.println("The number of words in the String are :  "+result);
    }
}


Output:

word count in string