How to check if a string is a palindrome ignoring case and non-alphanumeric characters in C

1 Answer

0 votes
#include <stdio.h>
#include <ctype.h>

int isPalindrome(const char *str) {
    char filtered[512];  
    int len = 0;

    // Filter out non-alphanumeric characters and convert to lowercase
    for (int i = 0; str[i] != '\0'; i++) {
        if (isalnum((unsigned char)str[i])) {
            filtered[len++] = tolower((unsigned char)str[i]);
        }
    }
    filtered[len] = '\0';

    printf("%s\n", filtered);

    // Check if the filtered string is a palindrome
    for (int i = 0; i < len / 2; i++) {
        if (filtered[i] != filtered[len - 1 - i]) {
            return 0;  // Not a palindrome
        }
    }

    return 1;  // Is a palindrome
}

int main() {
    const char *input = "+^-Ab#c!D 50...#  05*()dcB[]A##@!$";

    if (isPalindrome(input)) {
        printf("The string is a palindrome.\n");
    } else {
        printf("The string is not a palindrome.\n");
    }

    return 0;
}



/*
run:
  
abcd5005dcba
The string is a palindrome.
  
*/

 



answered Aug 9, 2025 by avibootz
...