//Palindrome analyzer analyzes a string to see if it reads the same forwards and backwards //ignoring all punctuation //uses C++ string objects #include //enables character functions #include #include //header to use C++ strings using namespace std; //function returns true if the phrase is a palindrome, ignoring all characters except letters and digits bool isPalindrome(string phrase); bool isPalindrome(string s, int left, int right); //overloaded recursive fcn string strip(string &phrase); void convertLower(string &s); int main() { string phrase; //input string with possible whitespace string stripped; //string containing only alphanumeric chars. cout << "Enter a phrase to analyze "; getline(cin, phrase); stripped = strip(phrase); //using a fcn defined in program // convertLower(stripped); if (isPalindrome(stripped)) //use iterative method cout << phrase << " is a palindrome "; else cout << phrase << " is not a palindrome "; cout << endl; if (isPalindrome(stripped, 0, stripped.length()-1)) //use recursive methods cout << phrase << " is a palindrome "; else cout << phrase << " is not a palindrome "; cout << endl; return 0; } // Determines if a string containing only lower case letters and digits is a palindrome // Recursive method bool isPalindrome(string s, int left, int right) { bool flag = true; if (left >= right) //have reached the middle of the string? return flag; if (s.at(left) == s.at(right)) flag = isPalindrome(s, left + 1, right - 1); else flag = false; return flag; } //Determines if a string containing only lower case letters and digits is a palindrome //Iterative method bool isPalindrome(string s) { char left, right; for (unsigned k = 0; k < s.length()/2; k++) { int length = s.length(); left = s.at(k); right = s.at(length -(k+1)); //Fix me! if ( left != right ) //compare chars on left and right ends return false; } return true; } //end isPalindrome() //this function takes an input string called phrase and strips it down to letters and digits //converts to all lowercase and returns the stripped string string strip(string &phrase) { string copy1; for (unsigned i = 0; i < phrase.length(); i++) { if (isalnum(phrase.at(i))) //check if the character is a letter or digit { copy1.push_back(tolower(phrase.at(i))); //add the alphanumeric char to end of string } } cout << "***" << copy1 << endl; //debug output return copy1; } void convertLower(string &s) { for (int k = 0; k < s.length(); k++) s.at(k) = tolower(s.at(k)); //at extracts a character from the string }