Question

I'm trying to make a recursive method that returns a word backwards and puts dashes between it. Here is my code:

public static String expand (String word)
{
    if (word.length () <= 1)
    {
        return word; //Return Original word
    }
    else
    {
        return word.substring (word.length () + 1 , word.length ()) + "-" + expand (word.substring (word.length ()));
    }
}

It's not working; it is just returning one letter with a dash. How can I fix it?

Was it helpful?

Solution

public static String expand(String word) {
    if (word.length() <= 1) {
        return word; //Return Original word
    } else {
        return word.substring(word.length() - 1) + "-" + expand(word.substring(0, word.length() - 1));
    }
}

Hope this helps.

OTHER TIPS

you could do it with out using recursive, just like this:

String s = "value";
    StringBuilder sb = new StringBuilder();
    for (int i = (s.length() - 1); i >= 0; i--) {
        sb.append(s.charAt(i));
        sb.append("-");
    }

    System.out.println(sb.toString());
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top