Java program to find occurrences of palindrome words in a string

Here, we are implementing a java program that will read a string and check the palindrome words in string also find the occurrences of words in a given string.
Submitted by Chandra Shekhar, on January 08, 2018

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

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

Java String Programs »



Related Programs

ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT


Top MCQs

Comments and Discussions!




Languages: » C » C++ » C++ STL » Java » Data Structure » C#.Net » Android » Kotlin » SQL
Web Technologies: » PHP » Python » JavaScript » CSS » Ajax » Node.js » Web programming/HTML
Solved programs: » C » C++ » DS » Java » C#
Aptitude que. & ans.: » C » C++ » Java » DBMS
Interview que. & ans.: » C » Embedded C » Java » SEO » HR
CS Subjects: » CS Basics » O.S. » Networks » DBMS » Embedded Systems » Cloud Computing
» Machine learning » CS Organizations » Linux » DOS
More: » Articles » Puzzles » News/Updates

© https://www.includehelp.com some rights reserved.