I actually found a valuable piece of code on the
Java Tips website (
http://www.java-tips.org/index.php). The code uses StringTokenizer to split the string up and (similar to the split() method) and then uses a Stack to hold the reverse order. Here's the code:
import java.util.*;
public class StringReverseWord {
private static void doStringReverseWord() {
String a = "Rohit Khariwal Mohit Parnami";
Stack stack = new Stack();
// this statement will break the string into the words which are separated by space.
StringTokenizer tempStringTokenizer = new StringTokenizer(a);
// push all the words to the stack one by one
while (tempStringTokenizer.hasMoreTokens()) {
stack.push(tempStringTokenizer.nextElement());
}
System.out.println("\nOriginal string: " + a);
System.out.print("Reverse string: ");
// pop the words from the stack
while(!stack.empty()) {
System.out.print(stack.pop());
System.out.print(" ");
}
System.out.println("\n");
}