Friday, 5 September 2014

Program to reverse a given sentence in java

Write a program to reverse a sentence in Java

For example if you have a sentence "Quick brown fox jumped over a lazy dog",
your output should be "dog lazy a over jumped fox brown Quick"


package com.prasune.coding;

import java.util.Stack;
import java.util.StringTokenizer;

public class ReverseSentence {

      public static void main(String[] args) {
            System.out.println(getReverseString("Quick brown fox jumped over a lazy dog"));
      }

      public static String getReverseString(String str){
        StringTokenizer tokenizer = new StringTokenizer(str);
        Stack<String> stack = new Stack<String>();
        String reversedString = "";
        while(tokenizer.hasMoreTokens()){
          stack.push(tokenizer.nextToken());
        }
        while(!stack.empty()){
              reversedString = reversedString + stack.pop() + " ";
        }
        return reversedString.trim();
      }
}





No comments:

Post a Comment