/* * Program to check whether line of text is palindrome -- the same * backward as forward, ignoring case and characters other than letters * and digits. * * Also prints error message if line is too long for program. */ #include #include #include #include #define LINESIZE 100 bool is_palindrome(char * s); int main(void) { printf("enter a line of text:\n"); char line[LINESIZE]; fgets(line, sizeof(line), stdin); char *endptr = strchr(line, '\n'); if (endptr == NULL) { printf("line too long, maximum %zd\n", sizeof(line)); return 1; } *endptr = '\0'; printf("input '%s'\n", line); if (is_palindrome(line)) { printf("a palindrome\n"); } else { printf("not a palindrome\n"); } } bool is_palindrome(char * s) { char *p1 = s; char *p2 = s + strlen(s) - 1; while (p1 < p2) { while (!isalnum(*p1) && (p1 < p1+strlen(s))) ++p1; while (!isalnum(*p2) && (p2 >= s)) --p2; if (p1 >= p2) { return true; } if (tolower(*p1) != tolower(*p2)) { return false; } ++p1; --p2; } return true; }