Friday, March 27, 2015

Number of words in a String

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 .

For example :

Original String : "I love music"     

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

Output : 3

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

Please find the code below :

public class StringDemo
{
    static int i,c=0,res;
    static int getWordcount(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.getWordcount("I love music");
        //string is always passed in double quotes
        
        System.out.println("The number of words in the String are :  "+res);
    }
}

No comments:

Post a Comment