Daniel C. Daniel C. - 1 month ago 9
C Question

Why does my palindrome checking function always return false for palindromes?

I'm trying to check if a sentence is palindrome or not. Neither space nor punctuation matter.

Examples:

• Never odd or even

• A man a plan a canal Panama.

• Gateman sees name, garageman sees name tag

Netheir of this sentences passes true on my code.
On my first for I try to remove spaces, punctuation and transform upper letters in lower.

int palindrome(char *str){
int n,n2 = 0,i,j=0;
n = sizeof(str)/sizeof(char);
char nova[n];

for (i=0;i< n;i++){
if(str[i] >= 'A' && str[i] <= 'Z'){
nova[n2] = ('a' + str[i] - 'A');
n2++;
}
else if(str[i] >= 'a' && str[i] <= 'z'){
nova[n2] = str[i];
n2++;
}
}

i=0;
while (i < n2-1){
if (nova[i]!= nova[j]){
return 0;
}
i++;
j--;
}

return 1;
}

Answer

The existing answer is good, but there is another way to solve this problem, without using additional allocated memory. You don't really need to store the letters anywhere in order to compare them - you can use pointers to your original string.

int palindrome(char *str)
{
    int i = 0, j = strlen(str);
    while (i < j)
    {
        if (str[j] == '\0' || !isalpha(str[j]))
            --j; // skip the character on the right if it's not a letter
        else if (!isalpha(str[i]))
            ++i; // skip the character on the left if it's not a letter
        else if (tolower(str[i]) != tolower(str[j]))
            return 0; // letters are different? - not a palindrome
    }
    // all letters were equal? - a palindrome
    return 1;
}
Comments