Program to reverse a String
Program -1 Reverse String with input String from arguments
public class ReverseString{
 
  public static void main(String args[]){

    ReverseString obj = new ReverseString();
    System.out.println(obj.reverseString(args[0]));
  }
  

  public String reverseString(String str){
   
   String aux = "";
   for(int itr = str.length()-1;itr>=0;itr--){
     aux += str.charAt(itr);
   }
   return aux;
  } 
  

  
}
Running the program as : java ReverseString ekiras 
Output of the program : sarike


Program -2 : Reverse String with input from command line at runtime.
import java.io.*;

public class ReverseString{
 
  public static void main(String args[]){

    ReverseString obj = new ReverseString();
    System.out.println(obj.reverseString(obj.getStringFromUser()));
  }
  

  public String reverseString(String str){
   
   String aux = "";
   for(int itr = str.length()-1;itr>=0;itr--){
     aux += str.charAt(itr);
   }
   return aux;
  } 
  
  public String getStringFromUser(){

     try{
     System.out.println("Enter String to be reversed");
     BufferedReader br= new BufferedReader(new InputStreamReader(System.in));
     return br.readLine();
     }
     catch(Exception e){e.printStackTrace();}
     return "ekansh";
  }
  

  
}

Output of the above program :
Enter String to be reversed
ekiras

sarike

No comments :

Post a Comment