Question
print palindrome words in a given sentence and frequency of palindrome words.
Palindrome words are words that are the same backward and forward.
example:
pop reads same, backward or forward
mom reads same, backward or forward.
Enter a sentence
mom and dad are not at home
Palindrome words in sentence:
mom
dad
Number of palindrome words in given sentence:2
Share code with your friends
Share on whatsapp
Share on facebook
Share on twitter
Share on telegram
Code
import java.util.Scanner;
public class palindromeWordsAndFrequencyInSentence
{
public static void main(String[] args)
{
String sen="",wd="",wd1="";
char ch=' ',lastCharacter=' ';
int i=0,len=0,palindromeWordFrequency=0;
Scanner sc = new Scanner(System.in);
System.out.println("Enter a sentence");
sen = sc.nextLine();
len=sen.length();
lastCharacter=sen.charAt(len-1);
if(lastCharacter!='.')
{
sen=sen+".";
len++;
}
System.out.println("Palindrome words in sentence:");
for(i=0;i< len;i++)
{
ch=sen.charAt(i);
if(ch==' '||ch=='.')
{
if(wd.equalsIgnoreCase(wd1)==true)
{
System.out.println(wd);
palindromeWordFrequency++;
}
wd1="";
wd="";
}
else
{
wd=wd+ch;
wd1=ch+wd1;
}
}
System.out.println("Number of palindrome words in given sentence:"+palindromeWordFrequency);
}
}