I tried to use recursion to reverse a string but I got an output of numbers
public static String reverse(String str) {
if(str == null) {
return null;
}
if(str.length() > 1) {
int ch = str.charAt(0);
String withoutFirst = str.substring(1);
String reverseNoFirst = reverse(withoutFirst);
String result = reverseNoFirst ch;
return result;
}
return str;
}
CodePudding user response:
You need to declare ch
as a char
, not int
:
char ch = str.charAt(0);
CodePudding user response:
Replace "int ch = str.charAt(0)" with "String chr=String.valueOf(str.charAt(0));"