Create an Palindrome Checker in C++ with free Codes

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:

  1. 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).
  2. Comparison:
    • While left is less than right, compare the characters at these pointers.
    • If they are equal, move the left pointer one step forward and the right pointer one step backward.
    • If any characters don’t match, the string is not a palindrome.
  3. 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;
}

Palindromee Checker in C++ Language

Leave a Comment

Your email address will not be published. Required fields are marked *

Scroll to Top