ueg1990
ueg1990

Reputation: 1033

Reversing a sentence recursively in Java

I want to reverse a sentence recursively and below is my following code. I wanted to know what other bases cases shud i take care of. And for the base case if string is null, how should that be handled?

public String reverse(String s) {
int n = s.indexOf(' ');
if(n == -1)
    return s;
return reverse(s.substring(n+1))+" "+s.substring(0,n);

}  

Upvotes: 0

Views: 2775

Answers (2)

asteri
asteri

Reputation: 11572

The reverse of null is null, so that's easy:

if(s == null) return null;

Because your method has the potential to return null, then, I would also do some null checking before referencing the value in your return statement and trying to append to it. so, something like...

String reversed = reverse(s.substring(n+1));
if(reversed != null) return reverse + " " + s.substring(0,n);
else return s;

Everything else looks fine. You shouldn't need any other base cases. Of course, this will reverse the sentence exactly as-is, including punctuation and case information. If you want to do this kind of thing, more strenuous processing will be required.

To ensure appropriate upper- and lower-case structure, I'd probably do something like this in your normal base case:

if(n == -1) {
    s = s.toLowerCase();
    String firstLetter = new String(s.charAt(0));
    s = s.replaceFirst(firstLetter, firstLetter.toUpperCase());
    return s;
}

Punctuation gets a little more complicated, especially if you have more than just an ending period, exclamation point, or question mark.

Upvotes: 2

FordFulkerson
FordFulkerson

Reputation: 140

in your case, if the string is null, you can return an empty string (""). Returning a null will require you to handle the null in the calling functions and if you miss a case, you might encounter a NullPointerException

Upvotes: 0

Related Questions