I am trying to reverse a full string in java
For example, Good morning
so the output should return morning good
.
I am tried the below function
public static String reverse(String s)
{
if (s.isEmpty())
return s;
//int n = 0;
return reverse(s.substring(1)) + s.charAt(0);
}
But the above function is converting good morning
into gninrom doog
. My code working on each character, how I make it work on words. Any hint or guide/explanation will be appreciated.
I already been to this question but not solving my problem
Updated:
Trying the below code with the help of @snr answer and @NathanHughes comments
public static String reverse(String s)
{
int s1 = s.indexOf(" ");
if (s1 != -1)
{
return reverse(s.substring(s1+1)) + s.substring(0,s1);
}
else
{
return "-1";
}
}
But output is
-1good