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).
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.
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 .
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.")
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With