Search This Blog

Tuesday, December 14, 2010

Input a sentence & print the number of characters found in the longest word of the given sentence - ICSE Board Question 2009

/**
 * Write a program to input a sentence & print the number of characters
   found in the longest word of the given sentence.
   For example if S= "India is my country" then the output should be 7
 */
import java.io.*;
class questionSIX2009
{
    public static void main(String args[]) throws IOException
    {
        BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
        System.out.println("Enter a sentence :");
        String s=br.readLine();
       
        char ch;
        s=s+" ";
        int array[]=new int[50];
        int lenword=0;
        int lenstr=s.length();
        int j=0;
       
        System.out.println("The string entered by you is: " +s);
        for(int i=0; i<lenstr; i++)
        {
            ch=s.charAt(i);
            if(ch!=' ')
            {
                lenword++;
               
                System.out.print(ch);
            }
           
            if(ch==' ')
            {
                array[j]=lenword;
                j++;
                System.out.println("   The size is " + lenword + "characters");
                lenword=0;
                System.out.print("\n");
            }
        }
         int m=0;
        for(j=0; j<lenstr; j++)
        {
            if(array[j]>m)
            {
                m=array[j];
            }
        }
        System.out.println("The length of the longest word is = " +m);
    }
   
}

No comments:

Post a Comment