Word Reverse Algorithm in Java

Problem :

Write a program that takes an input as a single argument on the command line. This argument must be a file name, which contains rows of text. The program should print each row of text and reverse all individual words in it, leaving the word order, punctuation and any non-alphanumeric characters unmodified. A word is a sequence of alphanumeric characters (i.e. letters and numbers).

Example :

Input :  Q: What do you call a blind pre-historic animal?

Output : Q: tahW od uoy llac a dnilb erp-cirotsih lamina?

Source Code : (Note: There may be more optimised /simple code available)
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;

public class Reverse {
	public static void main(String args[]) throws IOException {

		String filename = args[0];

		FileReader fr = new FileReader(filename);
		BufferedReader bfr = new BufferedReader(fr);

		String str;

		while ((str = bfr.readLine()) != null) {

			StringBuffer buffer = new StringBuffer();
			char stringArray[];
			stringArray = str.toCharArray();
			for (int index = 0; index < stringArray.length; index++) {
				char c = stringArray[index];

				if (Character.isLetter(c) || Character.isDigit(c)) {
					buffer.append(c);
					if (index == (stringArray.length - 1)) {
						System.out.print(buffer.reverse().toString());
						buffer.trimToSize();
						buffer.delete(0, buffer.length());
					}
					continue;
				} else {
					System.out.print(buffer.reverse().toString());
					buffer.trimToSize();
					buffer.delete(0, buffer.length());
					System.out.print(c);
				}
			}
			System.out.print('\n');
		}
	}
}

Leave a Reply

Your email address will not be published. Required fields are marked *