Thursday, January 27, 2011

determine if a string is a palindrome or not

Always forgetting web-site passwords? Then, DataVault for Android is the application for you. 
Here is a link to the lite version. This version is free to try for 4 weeks.
And finally, here is a link to the full version.




Dammit, I'm mad!
The solution is to start comparing characters from the start of the string and the end of the string. Here is the function in it's entirety...
#include <iostream>

#include <cstring>


bool is_palindrome(const char *str)
{
    if( !str )
    {
        std::cout << "Parameter is null? Returning false\n";
        return false;
    }

    std::cout << "is_palindrome called '" << str << "'...\n";
    const char *end = ::strchr(str, '\0');
    while( end > str)
    {
        while(*str && !isalpha(*str) )
            ++str;
        while( !isalpha(*end) && end > str)
            --end;
        std::cout << "\tcomparing '" << *str << "' and " << *end << "'\n";
        if( tolower(*str) != tolower(*end))
            return false;
        ++str;
        --end;
    }
    return true;
}


int main(int argc, char **argv)
{
    std::cout << is_palindrome("hello") << "\n";
    std::cout << is_palindrome("A dog, a plan, a canal: pagoda.") << "\n";
    std::cout << is_palindrome("As I pee, sir, I see Pisa!  ") << "\n";
    std::cout << is_palindrome("Dentist? Sit Ned.") << "\n";
    return 0;
}


1 comment: