Hi all! I'm trying to write some code to check whether a string is a palindrome or not. It must ignore all the non-alphabet chars. For example, "Madam, I'm Adam." is considered a palindrome. I have two pieces of code below. Please tell me which one is better, and if there are better ones. Thank you!
Code:
#include <iostream>
#include <string>
#include <cctype>
bool isPalindrome(const std::string& s);
int main()
{
using std::cout;
using std::cin;
std::string s;
cout << "Enter string (Enter 'quit' to quit): ";
std::getline(cin, s);
while (s != "quit")
{
if (isPalindrome(s))
cout << "Yes, it is a palindrome.\n";
else
cout << "No, it is not a palindrome.\n";
cout << "Enter string. ('quit' to quit.): ";
std::getline(cin, s);
}
return 0;
}
bool isPalindrome(const std::string& s)
{
int i = 0;
int j = s.length() - 1;
while (i < j)
{
if (!std::isalpha(s[i]))
{
++i;
continue;
}
if (!std::isalpha(s[j]))
{
--j;
continue;
}
if (std::tolower(s[i++]) != std::tolower(s[j--]))
return false;
}
return true;
}
Code:
bool isPalindrome(const std::string& s)
{
int i;
std::string original;
std::string reversed;
for (i = 0; i < s.length(); ++i)
{
if (std::isalpha(s[i]))
original += std::tolower(s[i]);
}
for (i = s.length()-1; i >= 0; --i)
{
if (std::isalpha(s[i]))
reversed += std::tolower(s[i]);
}
if (original == reversed)
return true;
else
return false;
}