Effective way of checking if a given string is palindrome in C

Ani picture Ani · Oct 7, 2013 · Viewed 10.1k times · Source

I was preparing for my interview and started working from simple C programming questions. One question I came across was to check if a given string is palindrome. I wrote a a code to find if the user given string is palindrome using Pointers. I'd like to know if this is the effective way in terms of runtime or is there any enhancement I could do to it. Also It would be nice if anyone suggests how to remove other characters other than letters (like apostrophe comas) when using pointer.I've added my function below. It accepts a pointer to the string as parameter and returns integer.

int palindrome(char* string)
{
    char *ptr1=string;
    char *ptr2=string+strlen(string)-1;
    while(ptr2>ptr1){
        if(tolower(*ptr1)!=tolower(*ptr2)){
            return(0);
        }
        ptr1++;ptr2--;
    }
    return(1);
}

Answer

LihO picture LihO · Oct 7, 2013

"how to remove other characters other than letters?"

I think you don't want to actually remove it, just skip it and you could use isalpha to do so. Also note that condition ptr2 > ptr1 will work only for strings with even amount of characters such as abba, but for strings such as abcba, the condition should be ptr2 >= ptr1:

int palindrome(char* string)
{
    size_t len = strlen(string);

    // handle empty string and string of length 1:
    if (len == 0) return 0;
    if (len == 1) return 1;

    char *ptr1 = string;
    char *ptr2 = string + len - 1;
    while(ptr2 >= ptr1) {
        if (!isalpha(*ptr2)) {
            ptr2--;
            continue;
        }
        if (!isalpha(*ptr1)) {
            ptr1++;
            continue;
        }
        if( tolower(*ptr1) != tolower(*ptr2)) {
            return 0;
        }
        ptr1++; ptr2--;
    }
    return 1;
}

you might need to #include <ctype.h>