Monday, 18 August 2014

How to reverse String in Java

Reverse String in Java



Hi this is the frequent question that I faced in some of the interviews. So I choose this one to write as my first post.



We can reverse a String using StringBuffer or StringBuilder or without using these two by iteratively or recursively.
First we will see how to reverse a String using StringBuffer and StringBuilder reverse() method.




package com.interviewCodes.String;

public class ReverseStringDemo1 {

       public static void main(String[] args) {

      String orgStr = "Hello World";
      System.out.println("Original String : " + orgStr );
       // reverse a String using StringBuffer
       String revStr = new StringBuffer(orgStr).reverse().toString();
       System.out.println("Reversed String "+ revStr);
       // reverse a String using StringBuilder
       revStr = new StringBuilder(orgStr).reverse().toString();
       System.out.println("Reversed String : "+ revStr);
       }

}

Now we  will how to reverse a String without using StringBuffer and StringBuilder by iteratively or recursively.
package com.interviewCodes.String;

public class ReverseStringDemo2 {

       public static void main(String[] args) {

             String orgnStr = "Hello World";
             System.out.println("Original String : " + orgnStr );
             //reverse a String iteratively
             String revStr = reverse(orgnStr);
             System.out.println("Reversed String "+ revStr);
             //reverse a String recursively
             revStr = reverseRecursively(orgnStr);
             System.out.println("Reversed String "+ revStr);
       } 

       // iterative method to reverse a String
       public static String reverse(String str) {

              if (str == null || str.isEmpty()) {
                     return str;
              }
              String reverse = "";
              for (int i = str.length() - 1; i >= 0; i--) {
                     reverse = reverse + str.charAt(i);
              }
              return reverse;
       }

       // reverse a String recursivly
       public static String reverseRecursively(String str) {

              if (str == null || str.isEmpty() || str.length() < 2) {
                     return str;
              }

              return reverseRecursively(str.substring(1)) + str.charAt(0);

       }
}
     
But I prefered to use StringBuffer or StringBuilder libraries to reverse a String.Please suggest if there are another ways of reversing a String.Thanks for reading.


No comments:

Post a Comment

How to find the String that contains only alphabets

Today we will see how to  find list of Strings that contains only alphabets. In this post I did this with and without using regular expres...