Skip to content

Instantly share code, notes, and snippets.

@gnarl
Created April 22, 2012 01:16
Show Gist options
  • Save gnarl/2440662 to your computer and use it in GitHub Desktop.
Save gnarl/2440662 to your computer and use it in GitHub Desktop.
Recursive String Reverse
public class ReverseString {
public static void main(String[] argv) {
String origString = argv[0];
System.out.println(origString);
System.out.println(reverse(origString));
}
public static String reverse(String str){
char[] strAry = str.toCharArray();
strAry = reverseAry(strAry, 0);
return new String(strAry);
}
public static char[] reverseAry(char[] strAry, int index) {
int oppositeIndex = strAry.length - index - 1;
if(oppositeIndex > index) {
char tmp = strAry[index];
strAry[index] = strAry[oppositeIndex];
strAry[oppositeIndex] = tmp;
strAry = reverseAry(strAry, ++index);
}
return strAry;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment