Question
Frequency of Palindrome words in a given sentence.
ENTER THE SENTENCE
mom and dad are not at home
FREQUENCY 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
Java
Python
Java
import java.util.Scanner;
public class palindromeWordsInSentence
{
public static void main(String[] args)
{
String sen="",wd="",wd1="";
char ch=' ';
int i=0,len=0,count=0;
Scanner sc = new Scanner(System.in);
System.out.println("Enter a sentence:");
sen = sc.nextLine();
sen=sen+" ";
len=sen.length();
for(i=0;i< len;i++)
{
ch=sen.charAt(i);
if(ch==' ')
{
if(wd.equalsIgnoreCase(wd1)==true)
{
count=count+1;
}
wd1="";
wd="";
}
else
{
wd=wd+ch;
wd1=ch+wd1;
}
}
System.out.println("Frequency of Palindrome words in given sentence:"+count);
}
}
Python
sentence=input("Enter a sentence:")
#making all the characters in the given sentence to upper case
#using upper()
sentence=sentence.upper()
#split(' ') will split the sentence whenever a space is found
#and creates a list
words=sentence.split(' ')
numberOfPalindromeWords=0
for word in words:
reverseOfWord=""
for i in range(0,len(word)):
reverseOfWord=word[i]+reverseOfWord
if(word==reverseOfWord):
numberOfPalindromeWords=numberOfPalindromeWords+1
print("There are",numberOfPalindromeWords,"Palindrome word(s) in given sentence")