everyone. I am very new to java so I hope my question does not sound dumb, but I am encountering trouble with an online exercise.
Basically, I need to write a recursive method, in java, called reverse that accepts a String parameter and returns a string concatenated with its reverse. So, for example, if the string was "Java" it returns it as "JavaavaJ"
I worked out most of the code, but cannot figure out how to combine the two in the return method.
public static String reverse(String str) {
if ((null == str) || (str.length() <= 1)) {
return str;
}
return reverse(str.substring(1)) str.charAt(0);
}
CodePudding user response:
You'll want to prepend the string you're reversing with the first character as well. Something like this should work:
public String reverse(String str) {
if (null == str) {
return null;
}
if (str.length() <= 1) {
return str str;
}
return str.charAt(0) reverse(str.substring(1)) str.charAt(0);
}
Without prepending the first character, the recursion would just produce a reverse of the string. Similarly, appending the whole string twice when you are at the last character is needed as well (e.g., "a" reversed using this logic seems like it should produce "aa")
CodePudding user response:
Use the StringBuilder for that:
public static String reverse(String s){
return s new StringBuilder(s).reverse();
}