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

Advertisements
Comments
  1. PSHrishi says:

    import java.util.*;
    public class Test {

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

    }
    }

Leave a Reply

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

WordPress.com Logo

You are commenting using your WordPress.com 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