Simple Programming Exercises, Part III

May 31, 2006

How to determine if a C string is a palindrome.

I’ve heard that, in some job interviews, people have had to write a function that determines whether a string is a Palindrome. I don’t know whether this is true, but I thought it would be a good practice exercise. My C function operates on the following assumptions:

  • The string is just a regular C-style string with ASCII characters (no accent marks, Unicode characters, or anything like that).
  • Certain characters should be ignored when examining the string. For instance, “Madam, I’m Adam” is considered a Palindrome, despite the spaces and punctuation. For my purposes, the function will ignore the following characters: '-:;, .?!
  • Case should not be considered when examining the string. For instance, the string ABCDcba should be considered a palindrome.

I wrote a helper function called ignorable() to determine whether a given character should be considered or ignored. It is defined as follows:

short ignorable(char c)
{
    char* ignorable_char = "'-:;, .?!";
    int i;

    for (i=0; i < 10; i++)
{
        if (c == ignorable_char[i])
        {
        return 1;
        }
    }
    return 0;   
}

Here’s the palindrome function itself:

short palindrome(char* str)
{
    int last = strlen(str) - 1;
    char* m = str;
    char* p = &str[last];

    while (m < p)
    {
        if (ignorable(*m))
        {
            m++;
        }
        else if (ignorable(*p))
        {
            p--;            
        }
        else if (toupper(*m++) != toupper(*p--))
        {
            return 0;
        }
}
    return 1;
}