In this section, we are going to find out the number of palindromes from the string.
In this section, we are going to find out the number of palindromes from the string.In this section, we are going to find out the number of palindromes from the string. For this, we have allowed the user to input a sentence or string. This string is then break down into tokens using StringTokenizer class and using the StringBuffer class, we have reversed each token of the string. After that we have matched the tokens with the reversed words by ignoring cases. If they are same, the counter will count the number of palindromes.
Here is the code:
import java.util.*; class CountPalindromes { public static void main(String[] args) { int count = 0; Scanner input = new Scanner(System.in); System.out.print("Enter sentence: "); String str = input.nextLine(); StringTokenizer stk = new StringTokenizer(str); while (stk.hasMoreTokens()) { String words = stk.nextToken(); StringBuffer sb = new StringBuffer(words); String reversedWords = sb.reverse().toString(); if (words.equalsIgnoreCase(reversedWords)) { count++; } } System.out.println("Number of Palindromes in the specified string: " + count); } }
Output:
Enter sentence: Madam Elle How are you? Number of Palindromes in the specified string: 2 |