0

I have written a program to reverse the words in a string. if i/p is "The dog is chasing" then o/p should be "chasing is dog The"

public class String_reverse {

    public static void main(String[] args) {

        String input= "The dog is chasing";

        String[] arr= input.split(" ");
        String reverse="";
        for(int i=arr.length-1;i>=0;i--)
        {
            reverse+= ((reverse.equals(""))?"":" ")+arr[i];
        }
        System.out.println(reverse);

    }

}

But I don't know how to write this program using recursion. When I tried searching in stackoverflow, I could find reversing a string; but not reversing the words in a string.

Sethuraman Srinivasan
  • 1,528
  • 1
  • 20
  • 34
  • 3
    Just think about it in general terms first, not Java specifically. On any given recursive call, you have a current word, and a rest of the sentence. What would you do? Would you display the current word, then do the rest of the sentence? Or something else? Of course you need to be mindful of the case when you run out of words (or are on the last word). – lurker Nov 18 '15 at 00:54
  • 2
    Possible duplicate of [Reversing a String with Recursion in Java](http://stackoverflow.com/questions/9723912/reversing-a-string-with-recursion-in-java) – Raf Nov 18 '15 at 01:05
  • No . It's not duplicate. In that question, they are reversing a string. Eg: Hello to olleH – Sethuraman Srinivasan Nov 18 '15 at 01:08
  • @SethuramanSrinivasan It *is* the same thing, except you append the first word, not the first character, and with a space separator. – Andreas Nov 18 '15 at 01:18
  • @Andreas How do you substring an array? – Yassin Hajaj Nov 18 '15 at 01:20
  • @YassinHajaj What array? You are substring'ing the text (`input`). – Andreas Nov 18 '15 at 01:22
  • @Andreas But how do you the bound of the last word? I thought of array because OPs using split(); – Yassin Hajaj Nov 18 '15 at 01:22
  • @YassinHajaj In a recursive method you wouldn't use `split()`, since the method signature would be `String reverseWords(String text)`. – Andreas Nov 18 '15 at 01:23
  • Ok but this does not answer the question. How, in a String, do you know the bound of the last word? – Yassin Hajaj Nov 18 '15 at 01:24
  • @YassinHajaj Don't know what you mean by "bound of last word". You're at last word when there is only one word left. – Andreas Nov 18 '15 at 01:33

4 Answers4

2

Recursive method, using same logic as linked "duplicate", without use of split():

private static String reverseWords(String text) {
    int idx = text.indexOf(' ');
    return (idx == -1 ? text : reverseWords(text.substring(idx + 1)) + ' ' + text.substring(0, idx));
}

The logic is:

  1. Take first char/word
  2. If that is last char/word, return with it
  3. Perform recursive call with remaining text (excluding word-separating space).
  4. Append space (if doing word)
  5. Append first char/word from step 1
  6. Return result

As you can see, when applied to reversing text (characters) instead of words, it's very similar:

private static String reverseText(String text) {
    return (text.length() <= 1 ? text : reverseText(text.substring(1)) + text.charAt(0));
}

For people who like things spelled out, and dislike the ternary operator, here are the long versions, with extra braces and support for null values:

private static String reverseWords(String text) {
    if (text == null) {
        return null;
    }
    int idx = text.indexOf(' ');
    if (idx == -1) {
        return text;
    }
    return reverseWords(text.substring(idx + 1)) + ' ' + text.substring(0, idx);
}
private static String reverseText(String text) {
    if (text == null || text.length() <= 1) {
        return text;
    }
    return reverseText(text.substring(1)) + text.charAt(0);
}

Notice how the long version of reverseText() is exactly like the version in the linked duplicate.

Community
  • 1
  • 1
Andreas
  • 154,647
  • 11
  • 152
  • 247
1

This is a sample program which will do what you want recursively:

public class ReverseWords {
    public static void main(String args[]) {
        String s = "This is a test";
        reverse(s);
    }

    private static void reverse(String s) {
        if(s == null) return;
        String words[] = s.split(" ", 2);
        if (words.length < 2) reverse(null);
        else reverse(words[1]);
        System.out.print(words[0] + " ");
    }
}
Atri
  • 5,511
  • 5
  • 30
  • 40
1

Recursive methods could seem a bit hard when beginning but try to do the following :

  • Simplify the problem as much as possible to find yourself with the less complicated case to solve. (Here for example, you could use a sentence with two words).

  • Begin with doing it on a paper, use Pseudocode to help you dealing with the problem with the simplest language possible.

  • Begin to code and do not forget an escape to your recursion.


Solution

public static void main(String[] args) {
    String s = reverseSentence("This sentence will be reversed - I swear".split(" "));
    System.out.println(s);
}

public static String reverseSentence(String[] sentence){
    if (sentence.length <= 1){
        return sentence[0];
    }
    String[] newArray = new String[sentence.length-1];
    for (int i = 0 ; i < newArray.length ; i++){
        newArray[i] = sentence[i];
    }
    return sentence[sentence.length-1] + " " + reverseSentence(newArray);
}
Yassin Hajaj
  • 21,337
  • 9
  • 51
  • 89
  • A lot of overhead in array cloning, and requires caller to prepare the data by calling `split()`. – Andreas Nov 18 '15 at 01:35
1

You can refer to the following code.

  class ReverseString {

public static void main(String args[]) {
    String myString = "The dog is chasing";

    reverse(myString);
}

public static String reverse(String myString) {
    int space = myString.indexOf(" ");
    if (space != -1) {
        reverse(myString.substring(space + 1, myString.length()));
    }
    if (space == -1) {
        System.out.println(myString.substring(0, myString.length()));
    } else {
        System.out.println(myString.substring(0, space));
    }
    return myString;
}
}
ashisahu
  • 357
  • 3
  • 9