Home > Enterprise >  Function in C to check if a string is a palindrome
Function in C to check if a string is a palindrome

Time:01-24

The function should check if an input string is a palindrome. It should not be case sensitive, and must ignore every other character except letters and numbers. The thing I am having problems with is when the string is empty(that means only the spaces are elements of the string), and when the string has a lot of other characters, but no letters or numbers.

This is my code, and it works well, except in the cases stated above.

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

  int is_it_palindrome(const char* str){

    int lenght;
    lenght=strlen(str);

    const char *start=str 0;
    const char *end=str lenght-1;

    while(start<end){
        if(!isalnum(*start)){
            start  ;
        }
        else if(!isalnum(*end)){
            end--;
        }
        else if(toupper(*start)==toupper(*end)){
            start  ;
            end--;
        }
        else{
            return 0;
        }
    }

    return 1;
 }

int main() {
    
    printf ("%d", is_it_palindrome("    "));
    printf ("%d", is_it_palindrome("a"));
    printf ("%d", is_it_palindrome(",./!\n _[]{}@"));
    printf ("%d", is_it_palindrome(",./!\n _A[]{}@"));
    
return 0;
}

The function returns 0 if it is not a palindrome, and 1 if it is a palindrome. So the output here should be 0 1 0 1, but I get 1 1 1 1. I really don't know how to rewrite this program to contain the conditions that I need. I would really appreciate the help.

CodePudding user response:

A string containing no alphanumeric characters is not a palindrome according to your rules yet it doesn't ever reach return 0; cause you skip over non alpha numeric characters. To check it you have to add a flag that tracks if you have any alpha numeric characters at all. Additionally to detect the single alnum char I go to start <= end instead of start < end

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

int is_it_palindrome(const char* str) {
    int lenght;
    int has_alnum = 0;
    lenght=strlen(str);

    const char* start = str   0;
    const char* end = str   lenght - 1;

    while (start <= end) {
        if (!isalnum(*start)) {
            start  ;
        } else if (!isalnum(*end)) {
            end--;
        } else if (toupper(*start) == toupper(*end)) {
            has_alnum = 1;
            start  ;
            end--;
        } else {
            return 0;
        }
    }

    return has_alnum;
}

int main(void) {
    printf("%d", is_it_palindrome("    "));
    printf("%d", is_it_palindrome("a"));
    printf("%d", is_it_palindrome(",./!\n _[]{}@"));
    printf("%d", is_it_palindrome(",./!\n _A[]{}@"));

    return 0;
}
  • Related