How to check whether a string is a palindrome, ignoring spaces and case in C

1 Answer

0 votes
#include <stdio.h>
#include <ctype.h> // isspace // tolower
#include <string.h> // strcmp // strlen

// Function to check if a string is a palindrome
int isPalindrome(const char *str) {
    char normalizedStr[128], reversedStr[128];
    int j = 0;

    // Normalize the string: remove spaces and convert to lowercase
    for (int i = 0; str[i] != '\0'; i++) {
        if (!isspace(str[i])) {
            normalizedStr[j++] = tolower(str[i]);
        }
    }
    normalizedStr[j] = '\0'; // Null-terminate the string

    // Reverse the normalized string
    int len = strlen(normalizedStr);
    for (int i = 0; i < len; i++) {
        reversedStr[i] = normalizedStr[len - i - 1];
    }
    reversedStr[len] = '\0'; // Null-terminate the string

    // Check if the normalized string is equal to the reversed string
    return strcmp(normalizedStr, reversedStr) == 0;
}

int main() {
    printf("Is palindrome: %s\n", isPalindrome("A man a plan a canal Panama") ? "true" : "false");
    printf("Is palindrome: %s\n", isPalindrome("abcDefg") ? "true" : "false");

    return 0;
}


/*
run:

Is palindrome: true
Is palindrome: false

*/

 



answered May 16, 2025 by avibootz
edited May 16, 2025 by avibootz
...