Sunday 23 August 2015

Reverse a string using recursion


Reverse a string using recursion.
public class StringReverse {

 public static String getReverse(String str) {
  if (str == null || str.length() == 1)
   return str;
  return reverse(str);
 }

 private static String reverse(String str) {
  if (str.length() == 0)
   return "";
  return str.charAt(str.length() - 1)
    + getReverse(str.substring(0, str.length() - 1));
 }
}


Following is the unit test case for above application.

import static org.junit.Assert.assertTrue;

import org.junit.Test;

public class StringReverseTest {

 @Test
 public void test1() {
  assertTrue(StringReverse.getReverse("Hello").equals("olleH"));
  assertTrue(StringReverse.getReverse("He").equals("eH"));
  assertTrue(StringReverse.getReverse("").equals(""));
  assertTrue(StringReverse.getReverse("H").equals("H"));
  assertTrue(StringReverse.getReverse(null) == null);
 }
}


No comments:

Post a Comment