I'm currently trying to write a function that will check how many palindroms words are in a given string and return that number to main. My approach was to check the length of a string and copying into another in reverse and then comparing both. While checking each time I reach a blank space
#define _CRT_SECURE_NO_WARNINGS
#include <stdio.h>
#include <string.h>
int palindrom(char str1[81]);
int main(){
char str[81];
gets(str);
printf("%d pali\n", palindrom(str));
}
int palindrom(char str[81]) {
int i, j=0, k = 0, pali_count = 0, length = 0, flag=0;
char rev[81], c;
for (i = 0; str[i] != '\0'; i++){}//getting the string length
while (i >= 0) {//revrsing the string
rev[j++] = str[--i];
}
rev[j-1] = '\0';
printf("%s", rev);
length = j - 2;
k = length;
j = 0;
while (k >= 0) {
k--;
j++;
c = rev[k];
if (rev[k] != str[j])
flag++;
if (c == ' ') {
if (flag == 0)
pali_count++;
flag = 0;
continue;
}
return pali_count;
}
return 0;
}
There are plenty of mistakes in your code. Let me explain you one by one:
while loop
(where you check reverse string with current string) you returnpali_count
after one iteration which always be zero.And at last your whole algorithm is wrong. Check the below example:
Now Here is the solution:
space
Here is the code:
Sample I/O:
madam mm sabuj --> 2 pali
sabuj --> 0 pali