// CS19, Cabrillo College // Steve J. Hodges // ANSII C++ string class example // tests strings for palindrome-ness // This example is intended to replace // the palindrome example program from our textbook // I believe that program (09-06.cpp) has several flaws including: // * lack of use of standard library functions // * improper/inadequate/non-standard re-creation of same // * poor overall detection algorithm // (perhaps easier to understand but at the penalty of doing extra work) #include #include #include using std::string; using std::cin; using std::cout; using std::endl; string transformString(const string& s); bool isPalindrome(const string& s); // generate a string without punctuation // or whitespace // and all lowercase characters // by appending all non-punct characters // to a new string string transformString(const string& s){ string fixed=""; //initially empty char c; // a character to examine int sLength = s.length( ); for (int i = 0; i < sLength; i++){ c = s.at(i); if (!ispunct(c) && !isspace(c)) fixed += tolower(c); } return fixed; } //uses function transformString // compare first half of transformed string // to last half (in reverse) bool isPalindrome(const string& s){ string str=transformString(s); int len = str.length(); int half = len/2; for (int i=0; i< half; i++){ if (str.at(i) != str.at(len-1-i)) return false; } return true; } int main( ){ string str; cout << "Enter a candidate for palindrome test\n:"; getline(cin, str); if (isPalindrome(str)) cout << "is a palindrome."; else cout << "is not a palindrome."; cout << endl; return 0; }