Reversing a String by Word
String test = "Reverse this string"; Stack stack = new Stack(); StringTokenizer strTok = new StringTokenizer(test); while(strTok.hasMoreTokens()) { stack.push(strTok.nextElement()); } StringBuffer revStr = new StringBuffer(); while(!stack.empty()) { revStr.append(stack.pop()); revStr.append(" "); } System.out.println("Original string: " + test); System.out.println("\nReversed string: " + revStr);
The output of this code fragment will be
Original string: Reverse this string Reversed string: string this Reverse
As you can see, reversing a string by word is more complex than reversing a string by character. This is because there is built-in support for reversing a string by character, but there is no such built-in support for reversing by word. To accomplish this task, we make use of the StringTokenizer and the Stack classes. Using StringTokenizer, we parse each word out of the string and push it onto our stack. After we’ve processed the entire string, we iterate through the stack, popping each word off and appending to a string buffer that holds the reversed string. A stack that has the property of last item in becomes the first item out. Because of this property, the stack is often referred to as a LIFO (last in, first out) queue. This makes the reverse successful.
See the phrase covered in the section, “Parsing a Comma-Separated String” in this chapter for more uses of the StringTokenizer class.