简体   繁体   中英

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;
}

line 4: you want to get the count of elements by sizeof .

But if you transfer your arguments to function by pointer.

  n = sizeof(str)/sizeof(char);

n will always be 4 (on 32 bit platforms). Instead, use

  n = strlen(str)

(need to #include <string.h> ) if it is a string format in c.

Ok, now with all the modifications it works. Thanks guys.

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

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

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

return 1;
}

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;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM