Home Tutorial Java Core Java Reverse words of the String

 
 

Share on Google+Share on Google+
Java Reverse words of the String
Posted on: October 26, 2009 at 12:00 AM
Advertisement
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
Advertisement

Related Tags for Java Reverse words of the String:


Follow us on Twitter, or add us on Facebook or Google Plus to keep you updated with the recent trends of Java and other open source platforms.

Posted on: October 26, 2009

Recommend the tutorial

Advertisements Advertisements
 

 

 

DMCA.com