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:
- Take first char/word
- If that is last char/word, return with it
- Perform recursive call with remaining text (excluding word-separating space).
- Append space (if doing word)
- Append first char/word from step 1
- 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.