Win a copy of Programmer's Guide to Java SE 8 Oracle Certified Associate (OCA) this week in the OCAJP forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

String manipulation - mirror image

 
James White
Greenhorn
Posts: 23
Java Spring
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 10336
Eclipse IDE Hibernate Java
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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.
 
James White
Greenhorn
Posts: 23
Java Spring
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 23
Java Spring
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
BTW, thanks for the quick reply Paul.
 
Paul Sturrock
Bartender
Posts: 10336
Eclipse IDE Hibernate Java
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic