Wednesday, 19 October 2016

Java Program to Count Occurrence of words in a Sentence in 3 Ways


Method 1:

/* Java Program Example - Count Occurrence of Word in Sentence */
 
import java.util.Scanner;

public class JavaProgramWORDOccur
{
   public static int countWords(String str)
    {
        int count = 1;
        for(int i=0; i<=str.length()-1; i++)
        {
            if(str.charAt(i) == ' ' && str.charAt(i+1) != ' ')
            {
                count++;
            }
        }
        return count;
    }
   public static void main(String args[])
   {
        String sentence;
        Scanner scan = new Scanner(System.in);
       
        System.out.print("Enter a Sentence : ");
        sentence = scan.nextLine();
 
        System.out.print("Total Number of Words in Entered Sentence is " + countWords(sentence));
   }
}



Method   2 :

import java.util.StringTokenizer; 
 
public class SimpleStrTokenzier
{  
 public static void main(String args[])
{  
   int count=0;

   StringTokenizer st = new StringTokenizer("Hai Iam Sivasankar"," "); 
 
     while (st.hasMoreTokens())
     {  
         System.out.println(st.nextToken());  
         count++;
         
     }  
     
       System.out.print(count);
   }  
}  



Method  3:


class SplitExample
{  

   public static void main(String args[])
   {  

       String s1=  "core java programming "; 

       int count = 0;

       String[] words=s1.split(" ");
 
      for(String w:words)
     {   
         System.out.println(w);  
         count++;
      }  
     
       System.out.print("Number of words in a String  :  "  +count);
 
   }
}  


No comments:

Post a Comment