Friday, April 11, 2014

Reversing Sentences : Opposite ordering of words [Java]

/*First input line specifies the number of lines to read in the file

Input:
3
This is a line
this is another line
and yet another

Output:
Case #1: line a is This
Case #2: line another is this
Case #3: another yet and

*/

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.InputStreamReader;
import java.util.Vector;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class Codejam {
    public static void main(String[] args) throws Exception{
        BufferedReader br = new BufferedReader(new FileReader("d:\\INPUTFile.txt"));
        BufferedWriter bw = new BufferedWriter(new FileWriter("d:\\OUTPUTFile.txt"));
        Pattern p = Pattern.compile("\\w+");
        Matcher m = null;
        int nCase = Integer.parseInt(br.readLine());
        int i = 1;
        while(i<=nCase)
        {
            m = p.matcher(br.readLine());
            Vector<String> vec = new Vector<String>();
            while(m.find()){
                vec.add(m.group());
            }
            bw.write("Case #"+i+++": ");
            for(int j=vec.size();j>0;--j){
                bw.write(vec.elementAt(j-1)+" ");
            }
            bw.newLine();
            bw.flush();
        }
    }
}

No comments:

Post a Comment