/* * 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 * start, char * end); 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, line+strlen(line)-1)) { printf("a palindrome\n"); } else { printf("not a palindrome\n"); } } bool is_palindrome(char * start, char * end) { if (end <= start) { /* nothing more to check */ return true; } else if (!isalnum(*start)) { /* first character not a letter or digit -- skip */ return is_palindrome(start+1, end); } else if (!isalnum(*end)) { /* last character not a letter or digit -- skip */ return is_palindrome(start, end-1); } else if (tolower(*start) == tolower(*end)) { /* first, last characters match, ignoring case */ return is_palindrome(start+1, end-1); } else { /* first, last characters don't match, ignoring case */ return false; } }