Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Check if a string is palindrome

Tags:

c++

I need to create a program that allows a user to input a string and my program will check to see if that string they entered is a palindrome (word that can be read the same backwards as it can forwards).

like image 332
Wil Prim Avatar asked Dec 02 '11 20:12

Wil Prim


People also ask

How do you know if its a palindrome?

A simple method for this problem is to first reverse digits of num, then compare the reverse of num with num. If both are same, then return true, else false.

How do you check if a word is a palindrome in C++?

Explanation. Start with initializing a bool as true . This value will be set to false if the word is not a palindrome and will stay true if it is a palindrome. Run a for loop to iterate through half of the string, i.e., from i = 0 to i = lenOfStr/2 .

How do you reverse a string and check if its a palindrome?

Source Code casefold() # reverse the string rev_str = reversed(my_str) # check if the string is equal to its reverse if list(my_str) == list(rev_str): print("The string is a palindrome.") else: print("The string is not a palindrome.")


1 Answers

Note that reversing the whole string (either with the rbegin()/rend() range constructor or with std::reverse) and comparing it with the input would perform unnecessary work.

It's sufficient to compare the first half of the string with the latter half, in reverse:

#include <string>
#include <algorithm>
#include <iostream>
int main()
{
    std::string s;
    std::cin >> s;
    if( equal(s.begin(), s.begin() + s.size()/2, s.rbegin()) )
        std::cout << "is a palindrome.\n";
    else
        std::cout << "is NOT a palindrome.\n";
}

demo: http://ideone.com/mq8qK

like image 159
Cubbi Avatar answered Oct 07 '22 04:10

Cubbi