O'Reilly logo

Java™ Phrasebook by Timothy Fisher

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

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 ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required