Search code examples
javastringrecursionreverse

Using Recursion to Reverse a String


I am trying to reverse a String word by word using recursion. (Ex: "Hello my friend" is reversed to "friend my Hello") This is the code I have attempted to write for this method. I have tried multiple similar variations but the output is only ever the first or last word of the String. I believe the part that is "broken" is the first if statement, but I am not quite sure.

public static String reverse (String words) {
   Scanner sc = new Scanner(words);
   String backwards = "";

   if (sc.hasNext()) {
     String currentWord = sc.next();
     reverse(sc.nextLine());
     backwards = backwards + " " + currentWord;
   } //end if
   else {
     backwards = words;
   } //end else

   return backwards;
 }

I am aware that a few similar questions exist, but their answers have not seemed to help me understand my mistake(s).

Thanks!


Solution

  • Instead of using a Scanner, you can make use of an overload of String.split to split words around the first space:

    public static String reverse(String words) {
        String[] wordArr = words.split(" ", 2); // split into a maximum of 2 Strings
    
        if (wordArr.length > 1) { // If there is more than 1 word
            // return the first word (wordArr[0]),
            // behind the reverse of the rest of the String (wordArr[1])
            return reverse(wordArr[1]) + " " + wordArr[0];
        }
    
        return wordArr[0]; // else, just return the one word
    }