Code with Vinay

ISC practical papers › ISC 2007 › Question 2

Reverse the order of words in a sentence

ISC 2007 Computer Science Practical, Question 2 · Strings

The question

The input in this problem will consist of a number of lines of English text consisting of the letters of the English alphabet, the punctuation marks (‘) apostrophe, (.) full stop, (,) comma, (;) semicolon, (:) colon and white space characters (blank, newline).

Your task is to print the words of the text in reverse order without any punctuation marks other than blanks.

For example consider the following input text: This is a sample piece of text to illustrate this problem. If you are smart you will solve this right.

The corresponding output would read as: right this solve will you smart are you If problem this illustrate to text of piece sample a is This

Note: That is, the lines are printed in reverse order. Individual words are not reversed

Input format: The first line of input contains a single integer N ( < = 20), indicating the number of lines in the input. This is followed by N lines of input text. Each line should accept a maximum of 80 characters.

Output format Output the text containing the input lines in reverse order without punctuation except blanks as illustrated above.

Test your program for the following data and some random data.

SAMPLE DATA
INPUT:  2
Emotions,  controlled and directed to work, is character.
By Swami Vivekananda.
OUTPUT:
Vivekananda Swami By character is work to directed and controlled Emotions
INPUT:  1
Do not judge a book by its cover.
OUTPUT:
Cover its by book a judge not Do

Question: ISC 2007 Computer Science Paper 2 (Practical), Question 2, set by the Council for the Indian School Certificate Examinations (CISCE). Solution and video: Vinay Singh.

Java solution

ISC2007Q2.java Download GitHub
import java.util.*;
class Sentence{
    private String sentence, output;
    public Sentence(String lines){
        this.sentence=lines;
        output="";
        reverseWords();
    }
    private void reverseWords(){
        String words[] = sentence.split("[',;:.\n\t ]+");
        output=words[0];
        for(int i=1; i<words.length;i++){
            output=words[i]+" "+output;
        }
    }
    public String toString(){
        return output;
    }
}
class ISC2007Q2 {
    public static void main(String[] args) {
        Scanner in = new Scanner(System.in);
        String lines="";
        System.out.print("INPUT:\t");
        int N = in.nextInt();
        in.nextLine();
        for( int i=0;i<N; i++){
            lines+=in.nextLine();
        }
        Sentence obj = new Sentence(lines);
        System.out.println("OUTPUT:\n"+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.

Get the free PDF ₹0 ISC 2027 mock papers