New Tutorials:   NUMPY    TKINTER    KOTLIN    JAVASCRIPT    SASS/SCSS    PL/SQL    Matplotlib    C++ Programs
See the Tutorial List

C++ Program to check String Palindrome

Hello Everyone!

In this tutorial, we will learn how to demonstrate how to check if the String is Palindrome or not, in the C++ programming language.

Condition for a String to be Palindrome:

A String is considered to be a Palindrome if it is the same as its reverse.

Steps to check for String Palindrome:

  1. Take the String to be checked for Palindrome as input.

  2. Initialize another array of characters of the same length to store the reverse of the string.

  3. Traverse the input string from its end to the beginning and keep storing each character in the newly created array of char.

  4. If the characters at each of the positions of the old char array are the same as the new char array, then the string is a palindrome. Else it isn't.

Code:

#include <iostream>
#include <stdio.h>

//This header file is used to make use of the system defined String methods.
#include <string.h>

using namespace std;

int main()
{
    cout << "\n\nWelcome to Studytonight :-)\n\n\n";
    cout << " =====  Program to Determine whether String is Palindrome or not, in CPP  ===== \n\n";

    //String Variable Declaration
    char s1[100], c = 'a';
    int n1, i = 0;

    cout << "\n\nEnter the String you want to check : ";
    cin >> s1;

    //Computing string length without using system defined method
    while (c != '\0')
    {
        c = s1[i++];
    }

    n1 = i-1;
    char s2[n1+1];

    cout << "Length of the entered string is : " << n1 << "\n\n";

    i = 0;
    //Computing reverse of the String without using system defined method
    while (i != n1 + 1)
    {
        s2[i] = s1[n1 - i - 1];
        i++;
    }

    cout << "Reverse of the entered string is : " << s2 << "\n\n\n";

    i = 0;
    //Logic to check for Palindrome
    while (i != n1)
    {
        if (s2[i] != s1[i])
            break;

        i++;
    }

    if (i != n1)
        cout << "The String \"" << s1 << "\"" << " is not a Palindrome.";
    else
        cout << "The String \"" << s1 << "\"" << " is a Palindrome.";

    cout << "\n\n";

    return 0;
}

Output:

C++ string palindrome

We hope that this post helped you develop a better understanding of how to check string is palindrome or not in C++. For any query, feel free to reach out to us via the comments section down below.

Keep Learning : )