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);
}
The reverse of
nullisnull, so that’s easy:Because your method has the potential to return
null, then, I would also do some null checking before referencing the value in yourreturnstatement and trying to append to it. so, something like…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:
Punctuation gets a little more complicated, especially if you have more than just an ending period, exclamation point, or question mark.