Monday 28 October 2013

Printing a sentence in reverse order of words

 /*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 simple 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

That is, the lines are printed in reverse order.
Note:- 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 punctuations 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 by its book a judge not Do


Answer 2.*/
import java.io.*;
class Q2_2007
{
  //Data members
  private String para;
  private String newpara;
  int len;
  int n;
  //Constructor
  public Q2_2007()
  {
      para="";
      newpara="";
      len=0;
  }
  //Function to input string
  public void Input()
  throws IOException
  {
     BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
     System.out.print("Enter number of lines ::");
     n=Integer.parseInt(br.readLine());
     System.out.println("Enter a paragraph of "+ n + " lines ");
     para=br.readLine();
     para=" "+para;
     len=para.length();
  }
  //Function to reverse para
  public void Reversepara()
  {
      int i;
      String word="";
      char letter;
      for(i=(len-1);i>=0;i--)
      {
          letter = para.charAt(i);
          if(letter!='\'' && letter!='.'&&letter!=','&&letter!=';'&&letter!=':'&&letter!=' ')
            word=letter+word;
          else
          {
              newpara+=word;
              newpara+=" ";
              word="";
            }
        }
        System.out.println("\n new paragraph ::\n"+newpara);
    }
}


class Q2_2007main
{
   public static void main(String args[])
   throws IOException
    {
        Q2_2007 obj = new Q2_2007();
        obj.Input();
        obj.Reversepara();
    }
}

No comments:

Post a Comment