/* * determine whether a string is a palindrome */ #include #include #include #include bool is_palindrome(char *s) { char *p = s; /* start at first char and go forward */ char *q = s + strlen(s) - 1; /* start at last char and go back */ while (p < q) { while (!isalpha(*p)) ++p; while (!isalpha(*q)) --q; if (p >= q) return true; if (tolower(*p) != tolower(*q)) return false; ++p; --q; } return true; } void test_palindrome(char *s) { printf("'%s' %s a palindrome\n", s, is_palindrome(s) ? "is" : "is not"); } int main(void) { char line[80]; printf("enter a line of text, or \"tests\" for tests/examples\n"); fgets(line, sizeof line, stdin); char *eol = strchr(line, '\n'); if (eol == NULL) { printf("line too long, maximum %d\n", (int) sizeof line - 1); return 1; } *eol = '\0'; if (strcmp(line, "tests") == 0) { test_palindrome("a"); test_palindrome("ab ba"); test_palindrome("abcd"); test_palindrome("abba"); test_palindrome("A man, a plan, a canal -- Panama!"); } else { test_palindrome(line); } return 0; }