Program to accept a sentence which is terminated by ‘.’ or ‘?’ or ‘!’ only. Check for Palindromic Words and convert the non-Palindromic Words to Palindromic Words.
A Palindromic Word is a word which can be spelled same if it is reversed.
Example: “The water level is rising.”. The program is expected to generate new sentence that is “ThehT wateretaw level isi risingnisir”.
Java
import java.util.*;
public class CovPalindromicWord
{
public static void main(String args[])
{
String str="",nstr="",wrd="",rev="";
char ch=' ';
int l=0;
Scanner sc=new Scanner(System.in);
System.out.println("Enter a sentence ending with '.' or '?' or '!'");
str=sc.nextLine();
str=str.trim();
l=str.length();
ch=str.charAt(l-1);
if(!(ch=='.'||ch=='?'||ch=='!'))
{
System.out.println("Error! Sentence must be terminated by punctuation");
System.exit(1);
}
for(int i=0;i<l;i++)
{
ch=str.charAt(i);
if(ch==' '||ch=='.'||ch=='?'||ch=='!')
{
if(wrd.equalsIgnoreCase(rev))
{
nstr=nstr+wrd+" ";
}
else
{
rev=rev.substring(1);
nstr=nstr+wrd+rev+" ";
}
wrd="";
rev="";
}
else
{
wrd=wrd+ch;
rev=ch+rev;
}
}
System.out.println("New string: "+nstr);
}
}Java