JAVA PROGRAM TO REVERSE THE WORDS OF A STRING

 

In  this   approach   we  are  using  split()  method  to  reverse  the  words  of  a  string.

 

 

 

import  java.util.*;

 

public  class   ReverseWords {

        public  static  void  main(String  args[] ) {

        Scanner  sc=new   Scanner(System.in);

        System.out.println(“Enter  a  String”);

        String    str=sc.nextLine();

        String[ ]   words= str.trim().split(“\\s+”);

        StringBuilder    reverseString= new  StringBuilder();

    

     for(int  i=words.length-1;i>=0;i–) {

            reverseString.append(words[i]);

 

//Add  a  space  between  words

            if(i>0)  {

                reverseString.append(” “);

                }

              }

 

    System.out.println(“Reversed  string  is :”+reverseString.toString());

     }

    }

 

 

 

Leave a Comment

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