Monday, February 27, 2012

Reverse a String and Reverse a String without reversing Word

---------------------------------------------------------
Q) Reverse a String and Reverse a String without reversing Words.
Ans) 
//Program to "Reverse a String" and "Reverse a String but not reversing Words"
public class StringWordReverse {
    public static String splitPattern=" ";  //Based on this Word will be chosen
    public static void main(String[] args) {
        String original=new String("Deepak kumar is good");
        String reverseString=new String();
        
        //Reversing the string
        for(int i=original.length();i>0;i--){
            reverseString=reverseString+original.charAt(i-1);
        }
        System.out.println("original :"+original);
        System.out.println("reverseString :"+reverseString);
        
        //Now Reversing the word only
        String wordReversed=new String();
        String arr[]=reverseString.split(splitPattern);
        for(String ar:arr){
            String temp=new String();
            for(int i=ar.length();i>0;i--){
                temp=temp+ar.charAt(i-1);
            }
            wordReversed=wordReversed+temp+splitPattern;
        }
        System.out.println("wordReversed :"+wordReversed);
    }
}
//Output: 
original :Deepak kumar is good
reverseString :doog si ramuk kapeeD
wordReversed :good is kumar Deepak 
---------------------------------------------------------     

4 comments:

  1. thanks deepak kumar

    ReplyDelete
  2. class B
    {
    public static void main(String args[])
    {
    String str="India is great Country";
    String str2[]=str.split(" ");
    for(int y=str2.length-1;y>=0;y--)
    {
    System.out.print(str2[y]+" ");
    }
    }
    }

    ReplyDelete