OneBite.Dev - Coding blog in a bite size

Check If A String Is A Palindrome In C++

Code snippet for how to Check If A String Is A Palindrome In C++ with sample and detail explanation

A palindrome is a string that reads the same backward as forward, such as “radar” or “madam”. In computer programming, we often need to check if a string is a palindrome or not. In this article, we will discuss a simple way to check if a string is a palindrome in C++.

Code snippet to Check If A String Is A Palindrome In C++

Here is a simple code snippet that checks if a string is a palindrome or not in C++.

#include <iostream>
#include <algorithm>
using namespace std;

bool isPalindrome(string str) {
  string original_str = str;
  reverse(str.begin(), str.end());
  return (original_str == str);
}

int main() {
  string str;
  cout << "Enter a string: ";
  cin >> str;
  if(isPalindrome(str))
    cout << str << " is a Palindrome.";
  else
    cout << str << " is not a Palindrome.";
  return 0;
}

Code Explanation for Checking If A String Is A Palindrome In C++

In the above C++ code snippet, we have a function isPalindrome() that takes a string as input and returns true if the string is a palindrome and false if it’s not.

Explained step-by-step:

  1. We first declare a variable original_str and store the original input string in it.

  2. We then use the reverse() function from the algorithm library to reverse the string in place. This function takes two arguments, the beginning and the ending iterator of the sequence to be reversed.

  3. Next, we compare the reversed string with the original string using the == operator. If both are identical, then our original string is a palindrome and the function returns true. If not, it returns false.

  4. In our main() function, we take a string as input from the user and call the isPalindrome() function with this string.

  5. If the function returns true, it means the input string is a palindrome, so we print that the string is a palindrome. If not, we print that the string is not a palindrome.

This is a simple and effective way of checking if a string is a palindrome or not in C++. By understanding this, we learn how to use the reverse() function and compare strings in C++.

c-plus-plus