Skip to main content

Java String Program to find the smallest and longest word present in a sentence

Java Program to find the shortest and longest word present in a sentence 

import java.util.Scanner;
public class Q2 {
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        System.out.println("Enter a sentence: ");
        String str = sc.nextLine()+" ";
        str=str.toUpperCase();
        String w="",k="";
        String z = str;
        for(int i=0;i<str.length();i++)
        {
            char ch = str.charAt(i);
            if(ch==' ')
            {
                if(w.length()>k.length())
                {
                    k=w;
                }                
                w="";
            }
            else
                w=w+ch;
        }
        System.out.println("The longest word is "+k);
        w="";
        String l="";
  for(int i=0;i<z.length();i++)
  {
   char ch=z.charAt(i);
   if(ch==' ')
   {
    if(l.equals(""))
    {
     l=w;
    }
    if(w.length()<l.length())
    {
     l=w;
    }
    w="";
   }
   else
   {
    w=w+ch;
   }
  }
  System.out.println("The shortest word is "+l);
    }
}

Popular posts from this blog