| Author |
String manipulation - mirror image
|
James White
Greenhorn
Joined: Apr 22, 2003
Posts: 23
|
|
I need to know how to create the mirror image of string. For instance, if a string is originally "I want to display the mirror image", it should look like "image mirror the display to want I". I tried looking through the past posts, but gave up after going through 5-6 pages. If someone has a way of doing this, I would appreciate it. Thanks, JW
|
 |
Paul Sturrock
Bartender
Joined: Apr 14, 2004
Posts: 10336
|
|
|
Sounds like you need to split the String into individual words based on a delimiter of a space and reconstruct the string by looping back through the array. Check out the String JavaDocs and see if you notice a method that might help.
|
JavaRanch FAQ HowToAskQuestionsOnJavaRanch
|
 |
James White
Greenhorn
Joined: Apr 22, 2003
Posts: 23
|
|
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"); }
|
 |
James White
Greenhorn
Joined: Apr 22, 2003
Posts: 23
|
|
|
BTW, thanks for the quick reply Paul.
|
 |
Paul Sturrock
Bartender
Joined: Apr 14, 2004
Posts: 10336
|
|
|
Well, that would work fine. But it is more complicated than it perhaps needs to be, and there is a way that doesn't use a class that extends Vector.
|
 |
 |
|
|
subject: String manipulation - mirror image
|
|
|