Question
Print Reverse of given sentence while preserving positions of word using recursion
ENTER THE SENTENCE
the rain stopped
REVERSE OF SENTENCE the rain stopped IS eht niar eppots
Share code with your friends
Share on whatsapp
Share on facebook
Share on twitter
Share on telegram
Code
import java.util.Scanner;
public class ReverseOfSentence
{
public static String FindReverse(String wd,int i)
{
if(i>=0)
{
return wd.charAt(i)+ FindReverse(wd,i-1);
}
else
{
return "";
}
}
public static void main()
{
int i=0;
char ch=' ';
String sen="",word="",reverseSen="";
Scanner sc=new Scanner(System.in);
System.out.println("ENTER THE SENTENCE");
sen=sc.nextLine();
for(i=0;i< sen.length();i++)
{
ch=sen.charAt(i);
if(ch==' '||i==sen.length()-1)
{
reverseSen=reverseSen+FindReverse(word,word.length()-1)+" ";
word="";
}
else
{
word=word+ch;
}
}
System.out.print("REVERSE OF SENTENCE "+sen+" IS "+reverseSen);
}
}