Program to accept a sentence which is terminated by ‘.’ or ‘?’ or ‘!’ only. Arrange the words in ascending order of their length.
Example: “I love my Country”. The program should sort the sentence according to the word potential thus generating an output “I my love Country”.
Java
import java.util.*;
public class SordWordsLA
{
public static void main(String args[])
{
String str="",wrd="",temp="";
char ch=' ';
int l=0,count=0;
Scanner sc=new Scanner(System.in);
System.out.println("Enter a sentence ending with '.' or '?' or '!'");
str=sc.nextLine();
str=str.trim();
l=str.length();
ch=str.charAt(l-1);
if(!(ch=='.'||ch=='?'||ch=='!'))
{
System.out.println("Error! Sentence must be terminated by punctuation");
System.exit(1);
}
for(int i=0;i<l;i++)
{
ch=str.charAt(i);
if(ch==' '||ch=='.'||ch=='?'||ch=='!')
{
count++;
}
}
String w[]=new String[count];
int len[]=new int[count];
count=0;
for(int i=0;i<l;i++)
{
ch=str.charAt(i);
if(ch==' '||ch=='.'||ch=='?'||ch=='!')
{
w[count]=wrd;
len[count]=wrd.length();
wrd="";
count++;
}
else
{
wrd=wrd+ch;
}
}
for(int i=0;i<count;i++)
{
for(int j=0;j<count-1-i;j++)
{
if(len[j]>len[j+1])
{
len[j]=len[j]+len[j+1];
len[j+1]=len[j]-len[j+1];
len[j]=len[j]-len[j+1];
temp=w[j];
w[j]=w[j+1];
w[j+1]=temp;
}
}
}
System.out.print("Sorted string: ");
for(int i=0;i<count;i++)
{
System.out.print(w[i]+" ");
}
}
}Java