#include #include #include using namespace std; bool is_palindrome( const string& line ); int main() { cout << "Type in a sentence and I will determine\n" << "whether it's a palindrome or not.\n"; // e.g. "Madam, I'm Adam" ==> "madA m'I ,madaM" // ==> "madamimadam" // count how many sentences are palindromes unsigned int count = 0; string line; while ( getline( cin, line ) ) // CTRL-D or CTRL-Z to exit { if ( is_palindrome( line ) ) { count++; cout << "PALINDROME: " << line << endl; } } cout << "Found " << count << " lines containing palindromes.\n"; return 0; } bool is_palindrome( const string& line ) { // HINT: use a local string variable // to hold a copy of line without spaces, punctuation, etc. // (also converted entirely to lowercase) string temp; string::const_iterator i; for ( i = line.begin() ; i != line.end() ; i++ ) { if ( isalpha( *i ) ) // only copy over alpha characters { temp.push_back( tolower( *i ) ); // convert to lowercase } } // HINT: use two iterators to compare the first letter // with the last letter, then the second letter // with the second-to-last letter, etc. // (returning false if a mismatch occurs) string::const_iterator j; // e.g. "madamimadam" // ^ ^ // i j i = temp.begin(); j = temp.end(); // or tack on - 1; j--; // now we're pointing to the last element // while ( i != j ) <== only works if size is odd while ( i < j ) { // compare characters: if ( *i != *j ) { return false; } i++; j--; } return true; } // another approach: bool is_palindrome_in_place( const string& line ) { // HINT: use two iterators to compare the "normalized" // first letter with the "normalized" last letter, // then the "normalized" second letter to the // "normalized" second-to-last letter, etc. // (returning false if a mismatch occurs) return true; } // TO DO: find the longest palindrome sentence you can!