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. Note I don't cover it here, but you may also be interested in checking out a new addition to JDK 1.5, the Scanner class. The Scanner class is a simple text scanner which can parse primitive types and strings using regular expressions. |