Studyon Minte9.com
Algorithms (Codingbat)




Reverse String



Write a program in Java to reverse any String without using StringBuffer.

	%java
		package testexample2;

		import org.junit.Assert.*;
		import junit.framework.*;
			
		public class Test extends TestCase {
		    
		    public static void main(String[] args) {
			    
			assertEquals("cba", reverse("abc")); // StringBuffer
			assertEquals("", reverse(""));
			
			assertEquals("cba", reverseL("abc")); // Loop
			assertEquals("", reverseL(""));
			
			assertEquals("cba", reverseR("abc")); // Recursion
			assertEquals("", reverseR(""));
		    }

		    public static String reverse(String s) {
			return new StringBuffer(s).reverse().toString();
		    }

		    public static String reverseL(String s) {
			
			String r = "";
			int i = s.length();
			while (i > 0) {
			    r += String.valueOf(s.charAt(--i));
			}
			return r;
		    }

		    public static String reverseR(String s) {

			if (s.length() <= 1) return s;
			return s.charAt(s.length()-1) + reverseR(s.substring(0, s.length()-1));
		    }
		}