Home Tutorial Java Core Java Reverse words of the String

 
 

Java Reverse words of the String
Posted on: October 26, 2009 at 12:00 AM
In this Java Tutorial section, we are going to learn how to reverse the words of the string using in Java programming language.

Reverse words of the String Java Programming

In this section, we are going to reverse the words of the string. For this, we have allowed the user to enter the string. Then we have converted the string into tokens using StringTokenizer class. After that, we have used the reverse() method of class StringBuffer which return the reverse order of the tokens.

Here is the code:

import java.util.*;
public class ReverseWords{
public static void main(String[] args){
  System.out.print("Enter the string: ");
  Scanner input=new Scanner(System.in);
  String str=input.nextLine();
StringBuffer buffer = new StringBuffer(str);
StringTokenizer st = new StringTokenizer(buffer.reverse().toString()" ");
System.out.print("Reversed Words: ");

while(st.hasMoreTokens()){
StringBuffer sb= new StringBuffer(st.nextToken());
System.out.print(" "+sb.reverse());
}
}
}

Output:

Enter the string: java is a programming language
Reversed Words: language programming a is java

Related Tags for Java Reverse words of the String:


Ask Questions?

If you are facing any programming issue, such as compilation errors or not able to find the code you are looking for.

Ask your questions, our development team will try to give answers to your questions.