How to check whether a string is a palindrome, ignoring spaces and case in C++

1 Answer

0 votes
#include <iostream>
#include <algorithm> // reverse

bool isPalindrome(const std::string& str) {
    // Normalize the string: remove spaces and convert to lowercase
    std::string normalizedStr;
    for (char ch : str) {
        if (!isspace(ch)) {
            normalizedStr += std::tolower(ch);
        }
    }

    // Reverse the normalized string
    std::string reversedStr = normalizedStr;
    std::reverse(reversedStr.begin(), reversedStr.end());

    // Check if the normalized string is equal to the reversed string
    return normalizedStr == reversedStr;
}

int main() {
    std::cout << std::boolalpha; // for true / false output
    
    std::cout << "Is palindrome: " << isPalindrome("A man a plan a canal Panama") << std::endl;
    std::cout << "Is palindrome: " << isPalindrome("abcDefg") << std::endl;
}


/*
run:

Is palindrome: true
Is palindrome: false

*/

 



answered May 16, 2025 by avibootz
...