*STRING PROGRAMS*

HOW TO CHECK NUMBER OF SPACES AND WORDS IN A STRING USING JAVA PROGRAM.

logic:

Example: I am an ICSE student

The above sentence has 5 words and 4(5-1) spaces.So to find the number of words we have to find the number of spaces and add (+1) to it.  


 

import java .io.*;

 class words_spaces

 {

     public static void main(String args[])throws IOException

     {

         int l,i,count=0;

         String b ; // declaring variables to be used in the program

         char s,y;

         

         BufferedReader br=new BufferedReader(new InputStreamReader(System.in));

         System.out.println("enter the string");

         b=br.readLine();//to take input from the user

         l=b.length();//to count the length of the string

         

         for(i=0;i<l;i++)

         {

          

             if(b.charAt(i)==' ')

             {

             count++;

            }

           

        }

         System.out.println("the number of spaces are"+count);

          System.out.println("the number of  words are"+(count+1));

    }

    

}

  output:



 

Comments