Reverse the Words in the String

Posted: August 23, 2012 in Uncategorized

Q. Update the string in place such that words in the strings are reversed.

Eg. “Harsh is awesome!” should be reversed to “awesome! is Harsh”.


A. The trick here is to handle the spaces. The best solution I could think of was to reverse all the characters and than reverse each individual word.

Step 1 – !emosewa si hsrah

Step 2 – awesome! is harsh

  1. PSHrishi says:

    import java.util.*;
    public class Test {

    public static void main(String[] args) {
    Scanner in = new Scanner(;
    String s = in.nextLine();
    String[] arr = s.split(” “);
    Stack x = new Stack();
    for(String str : arr)
    for(String str : arr)
    System.out.print(x.pop() + ” “);


Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s