Question
program to print reverse of the sentence while preserving the position of words.
Enter a sentence
Quick brown Fox jumped over the lazy Dog.
given sentence:Quick brown Fox jumped over the lazy Dog.
Reverse of Sentence:kciuQ nworb xoF depmuj revo eht yzal goD.
Share code with your friends
Share on whatsapp
Share on facebook
Share on twitter
Share on telegram
Code
import java.util.Scanner;
public class reverseOfEachWordsInSentence
{
public static void main(String[] args)
{
String sen="",wd="",newSen="";
char ch=' ';
int i=0,len=0;
Scanner sc = new Scanner(System.in);
System.out.println("Enter a sentence");
sen = sc.nextLine();
len=sen.length();
if(sen.charAt(len-1)!='.')
{
sen=sen+".";
len=len+1;
}
System.out.println("given sentence:"+sen);
for(i=0;i< len;i++)
{
ch=sen.charAt(i);
if(ch==' '||ch=='.')
{
newSen=newSen+wd+ch;
wd="";
}
else
{
wd=ch+wd;
}
}
System.out.println("Reverse of Sentence:"+newSen);
}
}