Well, the easiest way I can think of is using the STL algorithm library--particularly the reverse() function template. It reverses the elements in a container--and a string is a kind of container. You pass it two parameters the position of the first element and the position of the last element (in the case of a string; reverse(myString.begin() myString.end()); ). Here's how I would do it (less getting the user input):
Code:
#include <iostream>
#include <string>
#include <algorithm>
#include <cctype>
class Palindrome {
public:
Palindrome(){}; // Does nothing
bool isPalindrome(string s) const {
size_t pos; // Position holder
string r; // This is a holder for the
// reverse of the input string
// Get rid of any leading spaces...
while(s[0] == ' ')
s.erase(0, 1);
// Get rid of any trailing spaces or new lines...
while( (s[s.size() - 1] == ' ') || (s[s.size() - 1] == '\n') )
s.erase(s.size() - 1, 1);
// Get rid of any punctuation...
while( (pos = s.find_first_of("`~!@#$%^&*()-_=+{}|[]\\:;\"\'<>,.?/\t\r\n")) != string::npos)
s.erase(pos, 1);
// Get rid of any double spaces...
while( (pos = s.find(" ")) != string::npos)
s.erase(pos, 1);
// Convert to uppercase (ignoring single spaces)...
while( (pos = s.find_first_of("abcdefghijklmnopqrstuvwxyz")) != string::npos)
s[pos] = toupper(s[pos]);
// Make sure it's not an empty string...
if(s.empty()){
// For demo, print message and bail...
cout << "Error: Empty String Entered!\n" << ends;
exit(0);
} // End if
// Copy the input string to a temp string...
r = s;
// Reverse the temp string...
reverse(r.begin(), r.end());
return (0 == s.compare(r));
} // End isPalindrome(string &)
bool isPalindrome(char * c) const {
string t; // Temp value for conversion
// Convert to string...
t = static_cast<string>(c);
// Pass to other method...
return this->isPalindrome(t);
} // End isPalindrome(char *)
}; // End class Palindrome
int main(int argc, char *argv[]){
Palindrome palindrome; // Class to evaluate
string s("otto"); // This is the input string
cout << s.c_str();
if(palindrome.isPalindrome(s))
cout << " is a ";
else
cout << " is not a ";
cout << "palindrome.\n" << ends;
} // End main()
Bookmarks