Search code examples
c++stringpalindrome

How to ignore whitespace and punctuation?


I wrote a palindrome checker function and it works for the most part, but if the whitespace or punctuation isn't in the middle of the string it says it isn't a palindrome.

i.e

First test:

Enter string to test for palindrome:

hannah

string is a palindrome.

Second test:

Enter string to test for palindrome:

han nah

string is a palindrome.

Third test:

Enter string to test for palindrome:

hann.ah

string is not a palindrome.

Fourth test:

Enter string to test for palindrome:

han.nah

string is a palindrome.

I was wondering if there is a way to ignore the whitespace and punctuation all together so that h.annah or hann ah would be considered a palindrom?

Here's my code:

void isPalindrome (string s){  
    if(equal(s.begin(), s.begin() + s.size()/2, s.rbegin()) )
        cout << "string is a palindrome. " << endl;
    else
        cout << "string is not a palindrome. " << endl;
}

int main(){
    string test1;
    cout << "Enter string to test for palindrome: " << endl;
    getline(cin, test1);

    isPalindrome(test1);

    string test2;
    cout << "Enter string to test for palindrome: " << endl;
    getline(cin, test2);

    isPalindrome(test2);

    string test3;
    cout << "Enter string to test for palindrome: " << endl;
    getline(cin, test3);

    isPalindrome(test3);

    return 0;
}   

Solution

  • Apply a filter to the string prior to the palindrome check.

    Here's one way.

    #include <string>
    #include <iostream>
    #include <algorithm>
    
    void isPalindrome (std::string s){  
        if(equal(s.begin(), s.begin() + s.size()/2, s.rbegin()) )
            std::cout << "string is a palindrome. " << std::endl;
        else
            std::cout << "string is not a palindrome. " << std::endl;
    }
    
    std::string remove_rubbish(std::string s)
    {
        auto is_rubbish = [](char c) 
                    { 
                        return std::ispunct(c) || std::isspace(c); 
                    };
    
        s.erase(std::remove_if(s.begin(), 
                               s.end(), 
                               is_rubbish), 
                s.end());
    
        return s;    
    }
    
    int main(){
        auto s= std::string("ha-n.n?a h");
        isPalindrome(remove_rubbish(s));
    
        return 0;
    }