How to check if a string is a palindrome ignoring case and non-alphanumeric characters in C++

2 Answers

0 votes
#include <iostream>
#include <algorithm>
#include <string>

bool isPalindrome(const std::string& str) {
    std::string filtered;
    
    // Filter out non-alphanumeric characters and convert to lowercase
    for (char ch : str) {
        if (std::isalnum(ch)) {
            filtered += std::tolower(ch);
        }
    }
    std::cout << filtered << "\n";
    
    // Check if the filtered string is a palindrome
    return std::equal(filtered.begin(), filtered.begin() + filtered.size() / 2, filtered.rbegin());
}

int main() {
    std::string input = "+^-Ab#c!D 50...#  05*()dcB[]A##@!$";

    if (isPalindrome(input)) {
        std::cout << "The string is a palindrome.\n";
    } else {
        std::cout << "The string is not a palindrome.\n";
    }
}



/*
run:
  
abcd5005dcba
The string is a palindrome.
  
*/

 



answered Aug 9, 2025 by avibootz
0 votes
#include <iostream>
#include <string>
#include <regex>

bool isPalindrome(const std::string& s) {
    // Use regex to remove non-alphanumeric characters
    std::regex nonAlphaNum("[^a-zA-Z0-9]");
    std::string cleaned = std::regex_replace(s, nonAlphaNum, "");

    // Convert to lowercase
    std::transform(cleaned.begin(), cleaned.end(), cleaned.begin(),
                   [](unsigned char c) { return std::tolower(c); });

    std::cout << cleaned << std::endl;

    // Check if the cleaned string is a palindrome
    return std::equal(cleaned.begin(), cleaned.begin() + cleaned.size() / 2, cleaned.rbegin());
}

int main() {
    std::string s = "+^-Ab#c!D 50...#  05*()dcB[]A##@!$";
    
    std::cout << std::boolalpha << isPalindrome(s) << std::endl;
}




/*
run:
  
abcd5005dcba
true
  
*/

 



answered Aug 10, 2025 by avibootz
edited Aug 10, 2025 by avibootz
...