Count palindrome words in a sentence

Given a string str and the task is to count palindrome words present in the string str.

Examples:

Input : Madam Arora teaches malayalam
Output : 3
The string contains three palindrome words (i.e.,
Madam, Arora, malayalam) so the count is three.

Input : Nitin speaks malayalam
Output : 2
The string contains two palindrome words (i.e.,
Nitin, malayalam) so the count is two.

countPalin() function counts the number of palindrome words by extracting every word of the string and passing it to checkPalin() function. An extra space is added in the original string to extract last word.
checkPalin() function check the word palindrome. It returns 1 if word is palindrome else returns 0. It makes sure that empty strings are not counted as palindrome as the user may enter more than one spaces in between or at the beginning of the string.

C++

filter_none

edit
close

play_arrow

link
brightness_4
code

/*C++ program to count number of palindrome
words in a sentence*/
#include <bits/stdc++.h>
using namespace std;
  
// Function to check if a word is 
// palindrome 
bool checkPalin(string word) 
    int n = word.length(); 
    transform(word.begin(), word.end(), word.begin(), ::tolower);
  
    for (int i = 0; i < n; i++,n--) 
    if (word.at(i) != word.at(n - 1)) 
        return false;    
    return true
  
// Function to count palindrome words 
int countPalin(string str) 
{        
    // to check last word for palindrome 
    str = str + " "
      
    // to store each word 
    string word = ""
    int count = 0; 
    for (int i = 0; i < str.length(); i++) 
    
        char ch = str.at(i); 
          
        // extracting each word 
        if (ch != ' '
            word = word + ch; 
        else
            if (checkPalin(word)) 
                count++; 
            word = ""
        
    
      
    return count; 
      
// Driver code 
int main() 
      
    cout<<countPalin("Madam Arora teaches malayalam")<<endl; 
                  
    cout<<countPalin("Nitin speaks malayalam")<<endl; 
  
// This code is contributed by nidhi16bcs2007

chevron_right


Java

filter_none

edit
close

play_arrow

link
brightness_4
code

/*Java program to count number of palindrome
words in a sentence*/
class GFG {
      
    // Function to check if a word is
    // palindrome
    static boolean checkPalin(String word)
    {
        int n = word.length();
        word = word.toLowerCase();
        for (int i=0; i<n; i++,n--)
           if (word.charAt(i) != word.charAt(n - 1))
              return false;       
        return true;
    }
      
    // Function to count palindrome words
    static int countPalin(String str)
    {        
        // to check last word for palindrome
        str = str + " ";
          
        // to store each word
        String word = "";
        int count = 0;
        for (int i = 0; i < str.length(); i++)
        {
            char ch = str.charAt(i);
              
            // extracting each word
            if (ch != ' ')
                word = word + ch;
            else {
                if (checkPalin(word))
                    count++;
                word = "";
            }
        }
          
        return count;
    }
      
    // Driver code
    public static void main(String args[])
    {
        System.out.println(countPalin("Madam "
                  + "Arora teaches malayalam"));
                    
        System.out.println(countPalin("Nitin "
                        + "speaks malayalam"));
    }
}

chevron_right


Python3

filter_none

edit
close

play_arrow

link
brightness_4
code

# Python3 program to count number of 
# palindrome words in a sentence
  
# Function to check if a word is palindrome
def checkPalin(word):
    if word.lower() == word.lower()[::-1]:
        return True
  
# Function to count palindrome words
def countPalin(str):
    count = 0
      
    # splitting each word as spaces as 
    # delimiter and storing it into a list
    listOfWords = str.split(" ")
  
    # Iterating every element from list 
    # and checking if it is a palindrome.
    for elements in listOfWords:
        if (checkPalin(elements)):
              
            # if the word is a palindrome 
            # increment the count.
            count += 1
    print (count)
  
# Driver code
countPalin("Madam Arora teaches malayalam")
countPalin("Nitin speaks malayalam")
  
# This code is contributed 
# by Ronit Shrivastava.

chevron_right


C#

filter_none

edit
close

play_arrow

link
brightness_4
code

// C# program to count number of 
// palindrome words in a sentence
using System;
  
class GFG
{
  
// Function to check if a word is 
// palindrome 
public static bool checkPalin(string word)
{
    int n = word.Length;
    word = word.ToLower();
    for (int i = 0; i < n; i++,n--)
    {
    if (word[i] != word[n - 1])
    {
        return false;
    }
    }
    return true;
}
  
// Function to count palindrome words 
public static int countPalin(string str)
{
    // to check last word for palindrome 
    str = str + " ";
  
    // to store each word 
    string word = "";
    int count = 0;
    for (int i = 0; i < str.Length; i++)
    {
        char ch = str[i];
  
        // extracting each word 
        if (ch != ' ')
        {
            word = word + ch;
        }
        else
        {
            if (checkPalin(word))
            {
                count++;
            }
            word = "";
        }
    }
  
    return count;
}
  
// Driver code 
public static void Main(string[] args)
{
    Console.WriteLine(countPalin("Madam "
               "Arora teaches malayalam"));
  
    Console.WriteLine(countPalin("Nitin "
                      "speaks malayalam"));
}
}
  
// This code is contributed by Shrikant13

chevron_right


Output:

3
2


My Personal Notes arrow_drop_up

Check out this Author's contributed articles.

If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.





Article Tags :
Practice Tags :


Be the First to upvote.


Please write to us at contribute@geeksforgeeks.org to report any issue with the above content.