Search code examples
cstringpalindromeword-count

How to get the total count of palindrome words found in a sentence


I am working on a program which accepts a long string as input (a sentence). The program will check the string and count the number of palindrome words found then return the count.

Example:

input:

_gig school level bye_

output:

_2._

How can I get the total count of palindrome words in a sentence?

Below is what I have coded so far.

/*
My basic idea is: 
1) I will retrieve words from a sentence using "if(s[i] == ' ')"
2) I will check if the word is a palindrome
3) If it is a palindrome, I will add the word to the count "count++"
*/

#include <stdio.h>
#include <string.h>

int main()
{
   char s[80],temp;
   int i,j, len, count;
   count = 0;

   gets(s);
   len=strlen(s);
   j = len - 1;

   for(i = 0; i < len; i++){
   if(s[i] == ' '){
        for(;i<j;i++,j--)
        {   
            if(s[i] != s[j])
            break;  
        }
        if(i>=j)
        {
            count++;
        }
    }
    if (i == len)
        break;
}

printf("%d", count);
return 0;
}

Solution

  • Your logic is not correct. I have written the code in your style and now you can easily understand the things and use this code directly wherever you want.

    Check this code

    #include<stdio.h>
    #include<string.h>
    
    int main()
    {
      int i,j,k,l,len,count = 0;
      char s[80];
    
      gets(s);
      len = strlen(s);
    
      for(i=0;i<len;i++)
      {
        if(s[i] != ' ' || s[i] != '\n')
        {
          for(j=i;j<len;j++)
          {
              if(s[j] == ' ' || s[j] == '\n')
                break;
          }
        }
    
        for(k=i,l=j-1;;)
        {
          if(s[k] != s[l])
            break;
          else if(k >= l)
          {
            count = count + 1;
            break;
          }
          else
          {
            k = k + 1;
            l = l - 1;
            continue;
          }
        }
    
        i = j;
      }
    
      printf("\n%d",count);
      return 0;
    }