Check if a string is palindrome

Just compare the string with itself reversed:

string input;

cout << "Please enter a string: ";
cin >> input;

if (input == string(input.rbegin(), input.rend())) {
    cout << input << " is a palindrome";
}

This constructor of string takes a beginning and ending iterator and creates the string from the characters between those two iterators. Since rbegin() is the end of the string and incrementing it goes backwards through the string, the string we create will have the characters of input added to it in reverse, reversing the string.

Then you just compare it to input and if they are equal, it is a palindrome.

This does not take into account capitalisation or spaces, so you’ll have to improve on it yourself.

Leave a Comment