Q:

Java program to find occurrences of palindrome words in a string

belongs to collection: Java String Programs

0

Given a string and we have to find occurrences of palindrome words using java program.

Example:

    Input: "MOM AND DAD ARE MY BEST FRIENDS."
    Output:
    Palindrome words are: "MOM", "DAD"
    Occurrences of palindrome words is: 2

 

All Answers

need an explanation for this answer? contact us directly to get an explanation for this answer

Program to find occurrences of palindrome words in string in java

import java.io.*;
import java.util.*;

class CheckPalindromeWords
{
	// create object of buffer class.
	static BufferedReader br=new BufferedReader (new InputStreamReader (System.in));
 
	// function to check palindrome
	boolean IsPalindrome(String s)
	{
		int l=s.length();
		String rev="";
		for(int i=l-1; i>=0; i--)
		{
			rev=rev+s.charAt(i);
		}
		if(rev.equals(s))
			return true;
		else
			return false;
	}
 
	public static void main(String args[])throws IOException
    {
		// create function of palindromewords.
		CheckPalindromeWords ob=new CheckPalindromeWords();
        
		// enter the sentence.
		System.out.print("Enter the sentence : ");
        String s=br.readLine();
        
        // to convert into upper case.
        s=s.toUpperCase();
 
        StringTokenizer str = new StringTokenizer(s,".?! ");
        int w=str.countTokens(); 
 
        String word[]=new String[w];
        for(int i=0;i<w;i++)
        {
            word[i]=str.nextToken();
        }
 
        int count=0;
        System.out.print("OUTPUT : ");
        for(int i=0; i<w; i++)
        {
            if(ob.IsPalindrome(word[i])==true)
            {
                count++;
                System.out.print(word[i]+" ");
            }
        }
 
        // To show the palindrome or not.
        if(count==0)
        System.out.println("No Palindrome Words");
        else
        System.out.println("\nNumber of Palindromic Words : "+count);
    }
}

Output

Enter the sentence : MOM AND DAD ARE MY BEST FRIENDS.
OUTPUT : MOM DAD 
Number of Palindromic Words : 2

 

need an explanation for this answer? contact us directly to get an explanation for this answer

total answers (1)

Java String Programs

This question belongs to these collections

Similar questions


need a help?


find thousands of online teachers now
Java program to swap first and last character of e... >>
<< String concatenation with primitive data type valu...