Sunday, December 18, 2022

Arrange the words of a sentence in descending order of their lengths

 import java.io.*;
import java.util.*;
public class Gcd 
{
    BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
    int i,j,x;
    String str,sArr[]; 
    StringTokenizer stk;
    void accept() throws Exception
    {
        
        x=0;
        System.out.print("Enter a sentence: ");
         str=br.readLine(); 
         stk=new StringTokenizer(str);
         i=stk.countTokens();
         sArr=new String[i];
         while(stk.hasMoreTokens())
         {
             sArr[x++]=stk.nextToken();
            }
            for(i=0;i<x-1;i++)
            {
                 for(j=i+1;j<x;j++)
                 {
                     if(sArr[i].length()<sArr[j].length())
                     {
                         str=sArr[i];
                         sArr[i]=sArr[j];
                         sArr[j]=str;
                        }
                    }
                }
                System.out.println("\nWords in decending order according to length as follows");
                for(i=0;i<x;i++)
                System.out.println(sArr[i]);
            }
         
                  
public static void main(String args[])throws Exception
{
    Gcd ob=new Gcd();
    ob.accept();
}
}

Sample Input Output

Enter a sentence: this is another test of desending order

Words in desending order according to length as follows
desending
another
order
this
test
is
of


No comments:

Post a Comment

Subscribe via email

Enter your email address:

Delivered by FeedBurner