How to Reverse String in Java using String Tokenizer

In this example learn how to reverse a String with a StringTokenizer. The StringTokenizer is used to break a String into tokens. Here we will use it in a slight different manner so that we can reverse the String.

  • We will get a StringTokenizer for the String(message), using the Constructor StringTokenizer(String str)
  • Create a new empty string(“reverseMessage”) to hold our reversed String.
  • Use the hasMoreTokens() and nextToken() method of StringTokenizer to get the tokens of our original String.
  • We will now append the new token at the begining of the exsiting String everytime and so our “reverseMessage” will have the reversed String
package com.javainterviewpoint.strtkenizerexamples;

import java.util.StringTokenizer;

public class StringTokenizerExample 
{
	public static void main(String[] args) 
	{
		String reverseMessage="";
		String message ="Reverse String in Java using String Tokenizer";
		/*We have passed message to our st object,
		 * which splits the String based on spaces(default delimiter) 
		 */
		StringTokenizer st = new StringTokenizer(message);
		/*hasMoreTokens methods returns a boolean which is used to 
		 * check if there exist a next token 
		 */
		while(st.hasMoreTokens())
		{
			reverseMessage = st.nextToken()+" "+reverseMessage;
		}
                System.out.println("Original String is :"+message);		
                System.out.println("Reversed String is :"+reverseMessage);
	}
}

Output

Original String is :Reverse String in Java using String Tokenizer
Reversed String is :Tokenizer String using Java in String Reverse

Leave a Reply

Your email address will not be published. Required fields are marked *