ISC practical papers › ISC 2009 › Question 3
Sort Words In A Sentence
ISC 2009 Computer Science Practical, Question 3 · Strings
The question
Read a single sentence which terminates with a full stop(.). The words are to be separated with a single blank space and are in lower case. Arrange the words contained in the sentence according to the length of the words in ascending order. If two words are of the same length then the word occurring first in the input sentence should come first. For both input and output, the sentence must begin in upper case.
Test your program for the following data and some random data. INPUT: The lines are printed in reverse order. OUTPUT: In the are lines order printed reverse.
INPUT: Print the sentence in ascending order. OUTPUT: In the print order sentence ascending.
INPUT: I love my country. OUTPUT: I my love country.
Question: ISC 2009 Computer Science Paper 2 (Practical), Question 3, set by the Council for the Indian School Certificate Examinations (CISCE). Solution and video: Vinay Singh.
Java solution
import java.util.*;
class Sentence {
private String sentence, word[], output;
public Sentence(String sentence) {
this.sentence = sentence.toLowerCase();
word = this.sentence.split("[ .]");
sort();
}
public void sort() {
String temp;
boolean swapped;
for (int pass = 0; pass < word.length - 1; pass++) {
swapped = false;
for (int position = 0; position < word.length - 1 - pass; position++) {
if (word[position + 1].length() < word[position].length()) {
temp = word[position + 1];
word[position + 1] = word[position];
word[position] = temp;
swapped = true;
}
}
if (!swapped)
break;
beautify();
}
}
public void beautify() {
output = Character.toUpperCase(word[0].charAt(0)) + word[0].substring(1);
for (int i = 1; i < word.length; i++) {
output += " " + word[i];
}
output = output.trim() + ".";
}
public String toString() {
return output;
}
}
public class ISC2009Q3 {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
System.out.print("INPUT:\t");
String sentence = in.nextLine();
Sentence obj = new Sentence(sentence);
System.out.println("OUTPUT:\t" + obj);
in.close();
}
}
All these solutions in one free book
Pragmatic Solutions to ISC Computer Science Practical Problems collects every program from 2004 to 2021 in a 202-page PDF.