Check if a string is a palindrome

Description: Write is_palindrome(std::string). Ignore the case and the spaces. Test “Madam”, “Nurses run” and “C++”.

Hint:

  • Clean the text, then compare it with its reverse.

Solution

#include <algorithm>
#include <cctype>
#include <iostream>
#include <string>

bool is_palindrome(std::string s) {
    std::erase_if(s, [](unsigned char c) { return !std::isalnum(c); });
    std::transform(s.begin(), s.end(), s.begin(), [](unsigned char c) { return std::tolower(c); });
    return std::equal(s.begin(), s.begin() + s.size() / 2, s.rbegin());
}

int main() {
    std::cout << std::boolalpha;
    for (std::string t : {"Madam", "Nurses run", "C++"}) {
        std::cout << t << " -> " << is_palindrome(t) << '\n';
    }
}
Output

Madam -> true
Nurses run -> true
C++ -> true

How it works

  • We remove everything which is not a letter or digit, and make the rest lower case.
  • std::equal compares the first half with the reversed second half.

Read C++ Strings.


Learn more about the similar topics:
Tutorials
No Content Found.
Exercises & Assignments
No Content Found.
Interview Questions & Answers
No Content Found.