Palindrome Checker
C++ Palindrome Checker:
#include <iostream>
#include <string>
#include <algorithm>
bool isPalindrome(const std::string &str) {
std::string temp = str;
std::transform(temp.begin(), temp.end(), temp.begin(), ::tolower);
temp.erase(std::remove_if(temp.begin(), temp.end(), ::isspace), temp.end());
std::string reversed = temp;
std::reverse(reversed.begin(), reversed.end());
return temp == reversed;
}
int main() {
std::string input;
std::cout << "Enter a string: ";
std::getline(std::cin, input);
if (isPalindrome(input)) {
std::cout << input << " is a palindrome." << std::endl;
} else {
std::cout << input << " is not a palindrome." << std::endl;
}
return 0;
}
- Include Necessary Libraries:
The code includes the necessary C++ standard libraries for input/output and string manipulation.
Define isPalindrome Function:
A function named
isPalindrome
is defined, which takes a constant reference to a string as a parameter and returns a boolean value.Convert String to Lowercase:
The input string is copied to a temporary string, and then transformed to lowercase using the
std::transform
function.Remove Whitespaces:
Whitespaces are removed from the temporary string using the
std::remove_if
anderase
functions.Reverse the String:
The reversed version of the temporary string is obtained using the
std::reverse
function.Check for Palindrome:
The original temporary string is compared with the reversed string, and a boolean result is returned based on whether they are equal.
Main Function:
- The
main
function reads a string input from the user, calls theisPalindrome
function, and prints the result based on the returned boolean value.