Wednesday, January 11, 2017

Java Count Number of Words in String

In this post, I will show you How to count number of Words in the String. It's easy via array and string class.




For example : "Hello World"
Result : 2.

Coding:


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("Java Tutorial for Begginers");
        //string is always passed in double quotes
        
        System.out.println("Result : " +res);
    }
}
Result : 3

Good luck!
Share:

0 comments:

Post a Comment

Total Pageviews