main.cpp
#include<iostream>
#include<string>
#include<cctype>
#include<algorithm>
#include<iterator>
using std::string;
using std::cin;
using std::cout;
using std::endl;
void FillString(string& str);
bool equal(string& str);
char& Convert(char& ch);
int main()
{
string str;
while (true)
{
cout << "(input 'quit' to quit)" << endl;
FillString(str);
if (str == "quit")
break;
if (equal(str))
cout << "It is a palindrome.\n\n";
else
cout << "It is NOT a palindrome.\n\n";
}
cout << "\nBye!";
cin.get();
cin.get();
}
void FillString(string& str)
{
cout << "Enter contents for a string: ";
// be carefull,not use cin >> str,otherwise when space is input, will show error
getline(cin, str);
}
// when forward and backward order is same,it is a palindrome
// ***start
// ## Approach of using transform() of STL
bool equal(string& str)
{
string strLower;
// all elements convert to lower, use iterator locate a destination
transform(str.begin(), str.end(), std::insert_iterator<string>(strLower, strLower.begin()), Convert);
// create a string of backward order
string rstr(strLower.rbegin(), strLower.rend());
// if the two are same,return ture
return strLower == rstr;
}
char& Convert(char& ch)
{
// upper to lower
if (isupper(ch))
ch = tolower(ch);
return ch;
}
// ***end
/*
// ***start
// ## Approach of using push_back() of string
bool equal(string& str)
{
string strLower;
// all elements convert to lower
for (int i = 0; i < str.size(); i++)
{
if(isalpha(str[i]))
strLower.push_back(tolower(str[i]));
}
// create a string of backward order
string rstr(strLower.rbegin(), strLower.rend());
// if the two are same,return ture
return strLower==rstr;
}
// ***end
*/