Search code examples
cpalindrome

Why does my palindrome function not work with spaces in C?


I wrote a palindrome function, which for those who don't know, means a function that takes in a word/phrase/sentence and returns true if that word/phrase/sentence is the same string reversed.

For some reason, my function works for cases with no spaces only.

isPalindrome("madam") returns true which is correct.

isPalindrome("nurses run") returns false which is not correct

Here's the function:

#include <stdbool.h>

bool isPalindrome(char* str){
    char* ptr;
    char* aux; 

    ptr = str; 

    while (*ptr != '\0') { 
        ++ptr;
    } 
    --ptr; 

    for (aux = str; ptr >= aux;) { 
        if (*ptr == *aux) { 
            --ptr; 
            aux++; 
        } 
        else{
            break;
        }  
    } 

    if (aux > ptr){
        return true;
    } 
    else{
        return false;
    }
}

Calling/Driver code:

printf("Question 6a: %s\n", isPalindrome("nurses run") ? "true" : "false"); // prints false - not expected
printf("Question 6b: %s\n", isPalindrome("madam") ? "true" : "false"); // prints true as expected

Is there any way I can accommodate for space characters in the original string?


Solution

  • In your for loop, you could skip over spaces. Check first two if statements right after the for loop.

    #include <stdbool.h>
    
    bool isPalindrome(char* str){
        char* ptr;
        char* aux; 
    
        ptr = str; 
        while (*ptr != '\0') { 
            ++ptr;
        } 
        --ptr; 
    
        for (aux = str; ptr >= aux;) { 
            if(*ptr == ' ') {
                --ptr;
                continue;
            }
            if(*aux == ' ') {
                aux++;
                continue;
            }
    
            if (*ptr == *aux) { 
                --ptr; 
                aux++; 
            } 
            else{
                break;
            }  
        } 
    
        if (aux > ptr){
            return true;
        } 
        else{
            return false;
        }
    }
    
    int main() {
        printf("Question 6a: %s\n", isPalindrome("nurses run") ? "true" : "false"); // prints true - as expected
        printf("Question 6b: %s\n", isPalindrome("madam") ? "true" : "false"); // prints true as expected
    }