Write a program in Java to enter a String and display all the palindrome words present in the String Sample Input : MOM AND DAD ARE NOT AT HOME Sample Output : MOM DAD
Answers
The program in Java to display all the palindrome words in a string entered is shown below:
import java.util.Scanner;
public class KboatPalinWords
{
public static void main(String args[])
{
Scanner in = new Scanner(System.in);
System.out.println("Please enter a sentence:");
str = str + " ";
String word = "";
int len = str.length();
for (int i = 0; i < len; i++)
{
char ch = str.charAt(i);
if (ch == ' ')
{
int wordLen = word.length();
boolean isPalin = true;
for (int j = 0; j < wordLen / 2; j++)
{
if (word.charAt(j) != word.charAt(wordLen - 1 - j))
{
isPalin = false;
break;
}
}
if (isPalin)
System.out.println(word);
word = "";
}
else
{
word += ch;
}
}
}
}
Output:
Please enter a sentence: MOM AND DAD ARE NOT AT HOME
Output: MOM DAD
#SPJ1