×

Java Programs

Java Practice

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



Comments and Discussions!

Load comments ↻





Copyright © 2024 www.includehelp.com. All rights reserved.