Sunday, March 15, 2020

How to Count number of words in the 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 .
How to Count number of words 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 .
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);
    }
}

No comments:

Post a Comment