Untitled

mail@pastecode.io avatar
unknown
plain_text
7 months ago
1.4 kB
0
Indexable
Never
import java.util.*;
class LongestWord
{
    public static void main(String args[])
    {
        int c=0,l=0;
        String s,ls="";
        Scanner in = new Scanner(System.in);
        System.out.print("Enter a sentence ");
        s=in.nextLine();
        s=s+" ";
        for(int i=0;i<=s.length()-1;i++)//To find the length of the longest word
        {
            char ch=s.charAt(i);
            if(ch!=' ')
            {
                c++;
            }
            else
            {
                if(c>l)
                {
                    l=c;
                    c=0;
                }
                else 
                    c=0;
            }
        }
        c=0;//to make sure to clear any garbage value in variable c
        
        
        for(int i=0;i<=s.length()-1;i++)//To find and display the longest word
        {
            char ch=s.charAt(i);
            if(ch!=' ')
            {
                c++;
                ls=ls+ch;
            }
            else
            {
                if(c==l)
                {
                    System.out.println("longest word "+ls);
                    break;
                }
                else
                {
                    c=0;
                    ls="";
                }
            }
        }
        
        System.out.println("The length of longest word is: "+l);
    }
}
Leave a Comment