Write a program to take a String as input then display only palindrome words found in the String and also display how many palindrome words found.
For example:
Enter a String
MOM AND dad are talking
Palindrome words: MOM dad
No. of such words: 2
for(i=s.length()-1;i>=0;i--)
{
c=s.charAt(i);
rev=rev+c;
} //To check palindrome words
import java.util.*;
class App {
static boolean palindromeWord(String word) {
String rev = "";
for (int i = word.length() - 1; i >= 0; i--) {
char c = word.charAt(i);
rev = rev + c;
} // To check palindrome words
return rev.compareToIgnoreCase(word) == 0;
}
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
System.out.println("Enter a String: ");
String inputWords[] = in.nextLine().split(" ");
int noWords = 0;
System.out.print("Palindrome words: ");
for (int i = 0; i < inputWords.length; i++) {
if (palindromeWord(inputWords[i])) {
System.out.print(inputWords[i] + " ");
noWords++;
}
}
System.out.println("\nNo. of such words: " + noWords);
in.close();
}
}
Comments
Leave a comment