fork download
  1. #include <cstring>
  2. #include <cctype>
  3. #include <iostream>
  4.  
  5. bool YPalindrome(const char* candidate)
  6. {
  7. const char* left = candidate;
  8. const char* right = candidate + std::strlen(candidate) - 1;
  9.  
  10. while (left <= right)
  11. {
  12. bool leftAlpha = std::isalpha(*left);
  13. bool rightAlpha = std::isalpha(*right);
  14.  
  15. if (leftAlpha && rightAlpha) // only compare alphabetic characters.
  16. {
  17. if (std::tolower(*left) != std::tolower(*right))
  18. return false;
  19.  
  20. ++left, --right;
  21. }
  22. else
  23. {
  24. if (!leftAlpha) // skip non-alphabetic characters.
  25. ++left;
  26.  
  27. if (!rightAlpha)
  28. --right;
  29. }
  30. }
  31.  
  32. return true;
  33. }
  34.  
  35. void reportIfPalindrome(const char* s)
  36. {
  37. std::cout << '"' << s << "\" ";
  38.  
  39. if (YPalindrome(s))
  40. std::cout << "is a palindrome.\n";
  41. else
  42. std::cout << "is not a palindrome.\n";
  43. }
  44.  
  45. int main()
  46. {
  47. const unsigned phrases = 4;
  48. const char* str [phrases] =
  49. {
  50. "Madam, I'm Adam.",
  51. "Ra cecar",
  52. "not a palindrome",
  53. "A man, a plan, a canal - Panama!"
  54. };
  55.  
  56. for (unsigned i = 0; i < phrases; ++i)
  57. reportIfPalindrome(str[i]);
  58. }
Success #stdin #stdout 0s 3340KB
stdin
Standard input is empty
stdout
"Madam, I'm Adam." is a palindrome.
"Ra cecar" is a palindrome.
"not a palindrome" is not a palindrome.
"A man, a plan, a canal - Panama!" is a palindrome.