ClownInTheMoon ClownInTheMoon - 9 months ago 46
Java Question

Recursion for printing out words in sentence backwards

I'm working on getting a method that prints the words of a sentence out backwards. I'm very close to a solution but am hitting a minor snag.

Here is my code:

public static String reverseString(String str) {

if (str.equals(""))
return "";

else {

int i = str.length() - 1;

while (!Character.isWhitespace(str.charAt(i))) {
if (i - 1 < 0)

return str.substring(i,str.length()) + reverseString(str.substring(0,i));


Now the problem is the that the output from my test:

String test = "This is a test.";


Is giving me this back:

test. a isThis

Now, when I try to bump up the index of the substring being returned and add in the spaces manually, it cuts off the "T" in "This". That is, if I decide to instead return as follows:

return str.substring(i+1,str.length()) + " " + reverseString(str.substring(0,i));

then I get back

test. a is his

Does anyone have any advice or pointers on my implementation in general?

Answer Source

You can change the return statement to this:

return str.substring(i, str.length()).trim() + " " + reverseString(str.substring(0, i));