Automation Using Selenium Webdriver
Showing posts with label Java program To Count the number of words in a String. Show all posts
Showing posts with label Java program To Count the number of words in a String. Show all posts

Wednesday 23 November 2016

Java program To Count the number of words in a String

Java program To Count the number of words in a String::



  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