Tuesday, February 28, 2017

Java Programming: Different ways to reverse a String


When I was still looking for a job, I noticed that most job programming exams will have at least one or two questions about string manipulation in Java. Reversing a string is one of the most common questions I encountered about string manipulation. You might think, “Oh, it’s just easy! I’ll just use the Java’s built-in API for string reversion”. Unfortunately, you will be asked to reverse a string without using the built-in API, either using iteration or recursive method. I suggest that you get familiar with either of those methods if you want to show your future employer that if there’s no API available, then you can always write your own implementation.

Without further ado, here are the different ways to reverse a string in Java.


public class StringReverseDemo {

     public static void main(String[] args){
         // Original string
         String origStr = "What a wonderful day today";
         System.out.println("Original string: " + origStr);
         
         String reversedStr;
         
         // Reverse a string using StringBuilder
         reversedStr = new StringBuilder(origStr).reverse().toString();
         System.out.println("Reverse a string using StringBuilder: " + reversedStr);
         
         // Reverse a string using iteration method
         reversedStr = reverseUsingIteration(origStr);
         System.out.println("Reverse a string using iteration method: " + reversedStr);
         
         // Reverse a string using recursive method
         reversedStr = reverseStringRecursively(origStr);
         System.out.println("Reverse a string using recursive method: " + reversedStr);
     }
     
     public static String reverseUsingIteration(String str) {
         StringBuilder builder = new StringBuilder();
         char[] strChars = str.toCharArray();
         
         for (int i = strChars.length - 1; i >= 0; i--) {
             builder.append(strChars[i]);
         }
         
         return builder.toString();
     }
     
     public static String reverseStringRecursively(String str) {
         // This condition handles one character string and empty string
         if (str.length() < 2) {
             return str;
         }
         
         return reverseStringRecursively(str.substring(1)) + str.charAt(0);
     }
}

Output

Original string: What a wonderful day today                                                          
Reverse a string using StringBuilder: yadot yad lufrednow a tahW                                     
Reverse a string using iteration method: yadot yad lufrednow a tahW                                  
Reverse a string using recursive method: yadot yad lufrednow a tahW

No comments:

Post a Comment