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.

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.





JavaT Phrasebook. Essential Code and Commands
Java Phrasebook
ISBN: 0672329077
EAN: 2147483647
Year: 2004
Pages: 166

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net