Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I detect a palindrome in C?

Tags:

c

I've been working through potential interview questions and one of them was to write a function in C to detect whether a given string was a palindrome or not.

I've gotten a pretty good start on it:

#include <stdio.h>
#include <stdbool.h>

bool isPalindrome(char *value);

bool isPalindrome(char *value)
{
    if (value == null)
        return false;

    char *begin = value;
    char *end = begin + strlen(value) - 1;

    while(*begin == *end)
    {
        if ((begin == end) || (begin+1 == end))
            return true;

        begin++;
        end--;
    }

    return false;
}


int main()
{
    printf("Enter a string: \n");
    char text[25];
    scanf("%s", text);

    if (isPalindrome(text))
    {
        printf("That is a palindrome!\n");
    }
    else
    {
        printf("That is not a palindrome!\n");
    }
}

However, I now want to ensure that I ignore spaces and punctuation.

What is the best way, given the code I have written above, to advance the pointers forward or backward should they encounter punctuation/spaces?

like image 317
Waldrop Avatar asked Mar 01 '10 04:03

Waldrop


1 Answers

change the loop to

while(begin < end) {
  while(ispunct(*begin) || isspace(*begin))
    ++begin;
  while(ispunct(*end) || isspace(*end))
    --end;
  if(*begin != *end)
    return false;
  ++begin;
  --end;
}
return true;
like image 167
Alex Martelli Avatar answered Nov 03 '22 00:11

Alex Martelli