How to Reverse a String (Sentence) in Java
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.
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.
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.