How to Reverse a String (Sentence) in Java

>> Saturday, April 21, 2012

Reverse a String the form of words we are taking the help of StringTokenizer class it is having six featured methods in its class. We can use two of them. First apply StringTokenizer on the String then Split the sentence to words using delimiter. Then push all the words into Stack class. At last pop all words from Stack.

We can form a reverse sentence in this easy way as show below diagram.



package com.javabynataraj;

import java.util.*;

/**
 * Show String Reversals
 * @version $Id: StringReverse.java,v 1.4 2012/04/14 17:56:18 muralidhar n $
 */
public class StringReverse {
  public static void main(String[] argv) {
    //
    String s = "Father Charles Goes Down And Ends Battle";

    // Put it in the stack frontwards
    Stack<String> myStack = new Stack<String>();
    StringTokenizer st = new StringTokenizer(s);
    while (st.hasMoreTokens()) myStack.push((String) st.nextElement());

    // Print the stack backwards
    System.out.print('"' + s + '"' + " backwards by word is:\n\t\"");
    while (!myStack.empty()) { 
      System.out.print(myStack.pop());
      System.out.print(' ');
    }
    System.out.println('"');
    
  }
}

Before going to compile this program you should aware of compiling packaged java program. And how to run a packaged class. You can find in the below output.



Digg Technorati Delicious StumbleUpon Reddit BlinkList Furl Mixx Google Bookmark Yahoo ma.gnolia squidoo newsvine live netscape tailrank mister-wong blogmarks slashdot spurl

1 comments:

Zukidaru Ru August 12, 2012 at 12:50 AM  

Thank you for your tutorial, it's probably a quite difficult for the beginner. But if you learn it well, then it will be easy.
A little writting about programming

Post a Comment

Related Posts Plugin for WordPress, Blogger...

Random Posts

JavabynataraJ - Find me on Bloggers.com Find me on blorner.com Technology Blogs JavabynataraJ Backlinks Blogarama - The Blog Directory

  © Blogger template Webnolia by Ourblogtemplates.com 2009

Back to TOP