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?
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;
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With