0% found this document useful (0 votes)
41 views

How To Reverse A String

This document provides code to reverse a string (sentence) in Java. It uses the StringTokenizer class to split the string into individual words. These words are then pushed onto a Stack. Finally, the words are popped off the stack to output the reversed sentence.
Copyright
© Attribution Non-Commercial (BY-NC)
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
41 views

How To Reverse A String

This document provides code to reverse a string (sentence) in Java. It uses the StringTokenizer class to split the string into individual words. These words are then pushed onto a Stack. Finally, the words are popped off the stack to output the reversed sentence.
Copyright
© Attribution Non-Commercial (BY-NC)
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 2

How to Reverse a String (Sentence) in Java

>> SATURDAY, APRIL 21, 2012

0digg
Tweet 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.

You might also like