Share on Google+Share on Google+

Count Palindromes from the string

Advertisement
In this section, we are going to find out the number of palindromes from the string.

Count 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

Advertisements

Posted on: February 13, 2010 If you enjoyed this post then why not add us on Google+? Add us to your Circles

Share this Tutorial Follow us on Twitter, or add us on Facebook or Google Plus to keep you updated with the recent trends of Java and other open source platforms.