Question
Input a sentence from the user and print palindrome words in a given sentence.
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
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=' ',lastCharacter=' ';
int i=0,len=0;
Scanner sc = new Scanner(System.in);
System.out.println("Enter a sentence");
sen = sc.nextLine();
sen=sen+" ";
len=sen.length();
System.out.println("Palindrome words in sentence:");
for(i=0;i< len;i++)
{
ch=sen.charAt(i);
if(ch==' ')
{
if(wd.equalsIgnoreCase(wd1)==true)
{
System.out.println(wd);
}
wd1="";
wd="";
}
else
{
wd=wd+ch;
wd1=ch+wd1;
}
}
}
}
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(' ')
print("Palindrome words in given sentence:")
for word in words:
reverseOfWord=""
for i in range(0,len(word)):
reverseOfWord=word[i]+reverseOfWord
if(word==reverseOfWord):
print(word)