Intro – Palindrome Checker in C++
A Palindrome is the sequence that reads the same backward as forward. For example, “radar” and “madam” are palindromes. Implementing a palindrome check in C++ involves verifying whether a given string or number remains unchanged when its character or digits are reversed.
Algorithm for Palindrome Checker
The algorithm for checking if a string is a palindrome involves the following steps:
- Initialization:
- Start with two pointers, one pointing to the beginning of the string (
left
) and the other pointing to the end of the string (right
).
- Start with two pointers, one pointing to the beginning of the string (
- Comparison:
- While
left
is less thanright
, compare the characters at these pointers. - If they are equal, move the
left
pointer one step forward and theright
pointer one step backward. - If any characters don’t match, the string is not a palindrome.
- While
- Termination:
- If the loop completes without finding mismatched characters, the string is a palindrome.
Project Codes
Complete Project Codes,
#include <iostream> #include <string> #include <cctype> bool isPalindrome(const std::string& str) { int left = 0; int right = str.length() - 1; while (left < right) { // Ignore non-alphanumeric characters while (!std::isalnum(str[left]) && left < right) { left++; } while (!std::isalnum(str[right]) && left < right) { right--; } // Convert characters to lowercase for case-insensitive comparison char leftChar = std::tolower(str[left]); char rightChar = std::tolower(str[right]); if (leftChar != rightChar) { return false; } left++; right--; } return true; } int main() { std::string input; std::cout << "Enter a string: "; std::getline(std::cin, input); if (isPalindrome(input)) { std::cout << "\"" << input << "\" is a palindrome.\n"; } else { std::cout << "\"" << input << "\" is not a palindrome.\n"; } return 0; }