Google+

Friday, December 27, 2013

How to reverse only words in a string in place using java ??

In this program you can reverse the words in a string without changing the order of placement of words using JAVA.

Example : -
original string : emoclew  ot   dehsaelnu-ofni  !! 
Reversed output : welcome to info-unleashed !!

Program :

package test;
import java.util.Scanner;
/**
 * @author Arun
 */
public class strrev {
   String original , reverse="";
   int i=0,t=0;
   void test()
   {   
    Scanner in = new Scanner(System.in);
    System.out.println("Enter a string to reverse : ");
    original = in.nextLine();
    int length = original.length();
    for (;i <length ;i++ ){
     if(Character.isWhitespace(original.charAt(i))||i == length-1)
       {
        disp(i);
       }           
     }
     System.out.println();
   }
   void disp(int l)
    {       
      for(int j = i;j>=t;j--)
       {
         reverse = reverse+original.charAt(j);
       }
      System.out.print(reverse);
      t=i;
      reverse =" ";
    }
   public static void main(String args[])
    {
        strrev s = new strrev();
        s.test();
    }
}


This will get the input from user and reverse the string.
Please give your valuable comments to improve the efficiency of code.

No comments:

Post a Comment