Academic Integrity: tutoring, explanations, and feedback — we don’t complete graded work or submit on a student’s behalf.

Java Write a recursive, string -valued method , reverse, that accepts a string a

ID: 3779031 • Letter: J

Question

Java

Write a recursive, string -valued  method , reverse, that accepts a string and returns a new string consisting of the original string in reverse. For example, calling reverse with the string goodbye returns the string eybdoog.

Reversing a string involves:

Nothing if the string is empty or has only 1 character (reversing a single character  string does not change anything)

Otherwise concatenate the last character with the result of reversing the string consisting of the second through the next-to-last character , followed by the first character . In the above example, you would concatenate the 'e' (last character of goodbye) with the result of calling reverse on oodby (the string from the second character to the next-to-last), with the 'g' (first character ).

Explanation / Answer


public class StringReverse {
   static String reverse(String s)
   {
       int l = s.length();
       if(l<=1)
       {
           return s;
       }
       return s.charAt(l-1)+reverse(s.substring(0, l-1));
   }
   public static void main(String[] args) {
       // TODO Auto-generated method stub
       System.out.println(reverse("NewYork"));
   }

}

Hire Me For All Your Tutoring Needs
Integrity-first tutoring: clear explanations, guidance, and feedback.
Drop an Email at
drjack9650@gmail.com
Chat Now And Get Quote