Programming Examples
Java program to print and count all the palindrome words in input sentence
A Palindrome is a word that may be read the same way in either direction.
Accept a sentence in UPPER CASE which is terminated by either †. “, †? †or †! “. Each word of the sentence is separated by a single blank space.
Perform the following tasks:
(a) Display the count of palindromic words in the sentence.
(b) Display the palindromic words in the sentence. Example of palindromic words:
MADAM, ARORA, NOON
Solution:
import java.util.*;
class PalindromeWords
{
public static void main(String arr[])
{
Scanner sc=new Scanner(System.in);
System.out.println("Enter Any String ");
String str1=sc.nextLine();
String rev="",word="";
int count=0;
str1=str1+" ";
System.out.println("Palindrome Words in Strings are : \n");
for(int a=0;a<
str1.length();a++)
{
if(str1.charAt(a)==' ')
{
if(word.equals(rev))
{
System.out.print(rev+" ");
count++;
}
rev="";
word="";
}
else
{
rev=str1.charAt(a)+rev;
word=word+str1.charAt(a);
}
}
System.out.println("\nNumber of Palindrome Words : "+count);
}
}
Output
nitin is a very good pop singer
Palindrome Words in Strings are :Â
nitin a popÂ
Number of Palindrome Words : 3