Java Reverse words of the String


 

Java Reverse words of the String

In this Java Tutorial section, we are going to learn how to reverse the words of the string using in Java programming language.

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

Ads