1. package com.javatutorial;
  2.  
  3. public class CountNumberofWords {
  4.  
  5.  public static void main(String[] args) {
  6.  
  7. String s="";
  8. int count=0;
  9.  
  10. Scanner in = new Scanner(System.in);
  11. System.out.println("Please enter a String");
  12.  s=in.nextLine();
  13.  
  14. char ch[]= new char[s.length()];    
  15.  
  16. for(int i=0;i<s.length();i++)
  17. {
  18.  
  19.     ch[i]= s.charAt(i);
  20.  
  21.     if( ((i>0)&&(ch[i]!=' ')&&(ch[i-1]==' ')) || ((ch[0]!=' ')&&(i==0)) )
  22.         count++;
  23.  
  24. }
  25. System.out.println("Number of words in given String: "+count);
  26.  
  27. }

  28. }


Output:

  1. Please enter a String
  2. Java Tutorial
  3. Number of words in given String: 2

Instance Of Java

We will help you in learning.Please leave your comments and suggestions in comment section. if you any doubts please use search box provided right side. Search there for answers thank you.
«
Next
Newer Post
»
Previous
Older Post

1 comments for Java program To Count the number of words in a String

Select Menu