ISC practical papers › ISC 2020 › Question 3
Sort words in a sentence
ISC 2020 Computer Science Practical, Question 3 · Strings
The question
Write a program to accept a sentence which may be terminated by either '.',',','?' or '!' only. The words are to be seperated by a single blank space and are in UPPER CASE.
Perform the following tasks:
(a). Check for validity of the accepted sentence only for the terminating character. (b). Arrange the words in ascending order of their length. If two or more words have the same length, then sort them alphabetcally. (c). Display the original sentence along with the converted sentence.
Test your program for the following data and some random data:
Example 1 INPUT AS YOU SOW SO SHALL YOU REAP. OUTPUT AS YOU SOW SO SHALL YOU REAP. AS SO SOW YOU YOU REAP SHALL
Example 2 INPUT SELF HELP IS THE BEST HELP. OUTPUT SELF HELP IS THE BEST HELP. IS THE BEST HELP HELP SELF
Example 3 INPUT BE KIND TO OTHERS. OUTPUT BE KIND TO OTHERS. BE TO KIND OTHERS
Example 4 INPUT NOTHING IS IMPOSSIBLE# OUTPUT INVALID INPUT
Question: ISC 2020 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 MyString {
private String sentence, words[];
public MyString(String sentence) {
this.sentence = sentence;
}
public boolean isValid() {
return ".,?!".indexOf(sentence.charAt(sentence.length() - 1)) >= 0;
}
public void arrange() {
String temp;
sentence = sentence.substring(0, sentence.length() - 1); // take everything except the last character
words = sentence.split(" ");
for (int i = 0; i < words.length - 1; i++) {
for (int x = 0; x < words.length - 1 - i; x++) {
if (words[x + 1].length() < words[x].length()) {
temp = words[x + 1];
words[x + 1] = words[x];
words[x] = temp;
} else if (words[x + 1].length() == words[x].length()) {
if (words[x + 1].compareTo(words[x]) < 0) {
temp = words[x + 1];
words[x + 1] = words[x];
words[x] = temp;
}
}
}
}
}
public String toString() {
String output = "";
// for( int i=0; i<words.length;i++){
// output+=words[i]+" ";
// }
for (String word : words) {
output += word + " ";
}
return output.trim(); // return output+"\b"
}
}
public class ISC2020Q3 {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
String sentence;
System.out.println("INPUT");
sentence = in.nextLine();
System.out.println("OUTPUT");
MyString str = new MyString(sentence);
if (str.isValid()) {
System.out.println(sentence);
str.arrange();
System.out.println(str);
} else {
System.out.println("INVALID INPUT");
}
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.