15

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).

cigien
  • 50,328
  • 7
  • 37
  • 78
Wil Prim
  • 1,767
  • 6
  • 35
  • 51
  • 1
    I would first start by clicking on the little "search" bar in the upper right, typing in "palindrome" and browsing through the dozens of possible answers across various languages.. – Mike Christensen Dec 02 '11 at 21:02
  • 4
    @MikeChristensen That's a question tagged C, the kinds of things one would gripe about when debating answers would be different in C++... – HostileFork says dont trust SE Dec 02 '11 at 21:03
  • 4
    Why on earth is this marked as duplicate to a `C` question with way inferior answers...? – ruohola May 23 '19 at 13:36
  • If you need to check if a vector of integers is a palindrome or not: [LINK](https://pastebin.com/ZT5k55rf). – xinthose May 07 '20 at 02:33

6 Answers6

71

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

Cubbi
  • 43,318
  • 13
  • 94
  • 159
52

Just compare the string with itself reversed:

string input;

cout << "Please enter a string: ";
cin >> input;

if (input == string(input.rbegin(), input.rend())) {
    cout << input << " is a palindrome";
}

This constructor of string takes a beginning and ending iterator and creates the string from the characters between those two iterators. Since rbegin() is the end of the string and incrementing it goes backwards through the string, the string we create will have the characters of input added to it in reverse, reversing the string.

Then you just compare it to input and if they are equal, it is a palindrome.

This does not take into account capitalisation or spaces, so you'll have to improve on it yourself.

Seth Carnegie
  • 70,115
  • 19
  • 169
  • 239
  • 3
    I would vote your answer up, except the obvious gripe: it's homework, provide an approach/algorithm, not the code. What has the op learned from this exercise, laziness pays. :( – Nim Dec 02 '11 at 21:53
  • It doesn't work when string has the odd number of characters. – Iti Shree Sep 28 '17 at 16:36
11
bool IsPalindrome(const char* psz)
{
    int i = 0;
    int j;

    if ((psz == NULL) || (psz[0] == '\0'))
    {
        return false;
    }

    j = strlen(psz) - 1;
    while (i < j)
    {
        if (psz[i] != psz[j])
        {
            return false;
        }
        i++;
        j--;
    }
    return true;

}

// STL string version:

bool IsPalindrome(const string& str)
{
    if (str.empty())
        return false;

    int i = 0;                // first characters
    int j = str.length() - 1; // last character

    while (i < j)
    {
        if (str[i] != str[j])
        {
            return false;
        }
        i++;
        j--;
    }
    return true;
}
sehe
  • 328,274
  • 43
  • 416
  • 565
selbie
  • 82,148
  • 13
  • 83
  • 154
  • 6
    sorry, the question is tagged C++ _and_ there is no justification to produce obfuscated code like this in this case (_ever_?). See [Cubbi's answer](http://stackoverflow.com/a/8362657/85371) for immediate proof – sehe Dec 02 '11 at 21:52
  • 7
    You really consider the code above as obfuscated? Cubbi's solution is just STL kung-fu. Nothing wrong with that. But the code above is the classic solution to the problem - just not using STL. To make you happy, I'll demonstrate a reasonable STL variation of the same solution. – selbie Dec 02 '11 at 23:04
  • admittedly it could be a lot worse. If you do the C++ (not necessarily STL) variant, let me remove my -1 – sehe Dec 02 '11 at 23:08
  • 1
    I don't know what you mean by the "C++" variant that isn't STL. Almost all C code is valid C++ code. When someone speaks of a "string" in C/C++, I think "pointer to character". The "string class" is merely an encapsulation of a char pointer with extra overhead and some nifty features. I've spent more years than I'll admit striving to make all lines of code I write readable, understandable, and maintainable. So you can see why I would get spazzed about my code being called "obfuscated". – selbie Dec 02 '11 at 23:20
  • have removed -1, I'd personally say that returning `false` for an empty string is a bug (one which would never have occurred when using std::equals, I might add). I'd also wager that common idiom would write the while loop as `for(int i=)` but - I guess that is down to habits – sehe Dec 02 '11 at 23:21
  • 2
    The code you wrote is C++, not STL. STL implies the use of STL features, such as iterators and algorithms. You use none of those. The C++-ness (in general) is in the fact that strings are first-class objects with managed lifetime and allocations. Also, strings contain null characters without problem. My point: _even if you dislike STL, the benefit of using C++ style is significant already; there should be no reason to use `char*` and `strlen` (because they are more error-prone and less flexible)_ – sehe Dec 02 '11 at 23:22
  • @sehe Just curious. How much does the flexibility of *string* costs in terms of memory footprint and performance? – Roman Byshko Dec 02 '11 at 23:45
  • @RomanB - my point exactly. I don't actually know. But I do know this. STL code is inherently harder to debug. And if you don't pay attention, you will likely have less performant code if you abuse STL primitives, classes, and helper funcs. – selbie Dec 02 '11 at 23:49
  • @sehe - I'm not sure I buy the "string is a first class object" comment. It's just another STL class from my perspective. Perhaps that has changed in C++11. Or perhaps I'm confusing STL with the the C++ runtime. Either way, the compiler doesn't treat "string" instances differnet from any other class instances. Can you site a reference that spells out the string library as native to C++ and not STL? If you are correct, I will have learned something new. – selbie Dec 02 '11 at 23:54
  • @RomanB: Just **[look at test.s](http://pastebin.com/FrDteYXD)** after `g++ -O2 -s -S -fno-exceptions` [`test.cpp`](http://pastebin.com/99PaAvTz). Better yet, just profile the darn thing – sehe Dec 03 '11 at 00:06
  • @selbie: **(a)** Re: debugging - there is simply less to debug. That helps **(b)** Re. 'native' or 'first-class': perhaps _[first-class wasn't clear to you](http://en.wikipedia.org/wiki/First-class_object#Definition)_ - my point is that first class citizens avoid a whole universe of bugs, without sacrificing performance; also, [there is no such thing as 'the STL'](http://stackoverflow.com/questions/5205491/whats-this-stl-vs-c-standard-library-fight-all-about). Also, yes `strings` are very much 'native' to the C++ standard: [§ 21.4 Class template basic_string](http://tinyurl.com/c-11-final). – sehe Dec 03 '11 at 00:13
0
// The below C++ function checks for a palindrome and 
// returns true if it is a palindrome and returns false otherwise

bool checkPalindrome ( string s )
{
    // This calculates the length of the string

    int n = s.length();

    // the for loop iterates until the first half of the string
    // and checks first element with the last element,
    // second element with second last element and so on.
    // if those two characters are not same, hence we return false because
    // this string is not a palindrome 

    for ( int i = 0; i <= n/2; i++ ) 
    {
        if ( s[i] != s[n-1-i] )
            return false;
    }
    
    // if the above for loop executes completely , 
    // this implies that the string is palindrome, 
    // hence we return true and exit

    return true;
}
-2

Reverse the string and check if original string and reverse are same or not

Madhu Kasic
  • 174
  • 1
  • 1
  • 10
-12

I'm no c++ guy, but you should be able to get the gist from this.

public static string Reverse(string s) {
    if (s == null || s.Length < 2) {
        return s;
    }

    int length = s.Length;
    int loop = (length >> 1) + 1;
    int j;
    char[] chars = new char[length];
    for (int i = 0; i < loop; i++) {
        j = length - i - 1;
        chars[i] = s[j];
        chars[j] = s[i];
    }
    return new string(chars);
}
varatis
  • 13,702
  • 22
  • 65
  • 111
  • 19
    If you're not a C++ guy, why answer a C++ question using pidgin C++ that doesn't come close to compiling? :-/ If offering advice in a language you don't know, my suggestion would be to use "obvious" pseudocode which is nearly English. (For instance, `Let L = Length of S` is a lot less likely to cause eye-rolling than `int length = s.Length`) – HostileFork says dont trust SE Dec 02 '11 at 21:09
  • Anyone familiar with code should be able to figure that out. jeez. I guess Hostile is the correct modifier for you. – varatis Dec 02 '11 at 21:21
  • 7
    What... I only noticed this doesn't even check for palindromes after about... 30 seconds. So, it is obfuscated _and_ not an answer? – sehe Dec 02 '11 at 21:54
  • 1
    @varatis I think my response was measured. I didn't downvote you. (Someone else did, and either did or didn't explain why.) I was making a suggestion on how you might provide feedback in a case like this *without* writing code that doesn't compile which is likely to confuse a new C++ programmer more than help them. And as for what a hostile fork is in software development, look it up... – HostileFork says dont trust SE Dec 02 '11 at 22:00