Create a gist now

Instantly share code, notes, and snippets.

What would you like to do?
Reverse String [for & recursive]
public class Main {
public static void main(String[] args) throws Exception {
System.out.println(reverse("0123456789"));
}
private static String reverse(String str) {
int size;
if((str == null) || (size = str.length()) == 0) {
return str;
} else if(size == 1) {
return str;
}
return new String(swap(str.toCharArray(), 0, size-1));
}
private static char[] swap(char[] str, int i, int j) {
char c = str[i];
str[i] = str[j];
str[j] = c;
return (i < j)? swap(str, ++i, --j) : str;
}
}
public class Main {
public static void main(String[] args) throws Exception {
System.out.println(reverse("0123456789"));
}
private static String reverse(String str) {
int size;
if((str == null) || (size = str.length()) == 0) {
return str;
} else if(size == 1) {
return str;
}
char[] _str = str.toCharArray();
char c;
for(int i = 0, j = size-1; i < j; i++, j--) {
c = _str[i];
_str[i] = _str[j];
_str[j] = c;
}
return new String(_str);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment