Get the latest news, exclusives, sport, celebrities, showbiz, politics, business and lifestyle from The VeryTime,Stay informed and read the latest news today from The VeryTime, the definitive source.

How to Write a Program to Check Whether a String Is a Palindrome or Not

6

C++

  • 1). Open a C++ program file. Insert the cursor at the top of the file.

  • 2). Type the following code:

    #include <iostream>

    #include <string>

    using namespace std;

    These lines include the necessary header files and set the namespace to use.

  • 3). Insert the cursor where you want to check for palindromes. Type the following code:

    string word;

    bool palindrome;

    cout << "Enter a string: ";

    cin >> word;

    The first line creates a string variable. The second creates a Boolean variable that holds the value of whether the string is a palindrome or not. The third line prompts the user to type in a string and the fourth saves it to the string variable.

  • 4). Type the following code:

    for (int x=0; x < word.length()-1; x++) {

    if (word[x] != ' ') {

    if (tolower(word[x]) != tolower(word[word.length()-(x+1)])) {

    palindrome = false;

    break;

    }

    else { palindrome = true; }

    }

    }

    The for loop starts checking the string. The first if statement checks to see if the character is a space. If so, it skips it. The next if statement converts the string to lowercase and checks it against the reversed string, character by character. If any of the characters do not match, the function breaks because the string is not a palindrome. Otherwise, it is a palindrome and the Boolean variable is set to true.

  • 5). Type the following code:

    if (palindrome) cout << "The string is a palindrome";

    else cout << "The string is not a palindrome";

    These lines check the palindrome variable and if it is true, it informs the user the string is a palindrome. If not, it tells the user it is not.

Source...
Subscribe to our newsletter
Sign up here to get the latest news, updates and special offers delivered directly to your inbox.
You can unsubscribe at any time

Leave A Reply

Your email address will not be published.