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 |
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.