Friday 3 January 2014

program to reverse a String in Java.

 Write a program to reverse a String in Java.



package programs;

import java.io.FileNotFoundException;
import java.io.IOException;
public class StringReverse {
   public static void main(String args[]) throws FileNotFoundException, IOException {

       //original string
       String stmt = "This is Program to Reverse a String";
       System.out.println("Actual  String: " + stmt);

       //reversed string using Stringbuffer
       String reverseStr = new StringBuffer(stmt).reverse().toString();
       System.out.println("Reversed String using StringBuffer: " + reverseStr);

       //iterative method to reverse String 
       reverseStr = reverseiteration(stmt);
       System.out.println("Reversed  String using Iteration: " + reverseStr);

       //recursive method to reverse String
       reverseStr = reverseRecursion(stmt);
       System.out.println("Reversed  String  using Recursion: " + reverseStr);

   }

   public static String reverseiteration(String str) {
       StringBuilder strBuilder = new StringBuilder();
       char[] Chars = str.toCharArray();

       for (int x =Chars.length - 1; x >= 0; x--) {
           strBuilder.append(Chars[x]);
       }
       return strBuilder.toString();
   }

   public static String reverseRecursion(String str) {

       //base case to handle one char string and empty string
       if (str.length() < 2) {
           return str;
       }
       return reverseRecursion(str.substring(1)) + str.charAt(0);

   } }


3 comments: