CptZpBrngn
CptZpBrngn

Reputation: 35

C++ character in string comparision

I'm getting acquainted with c++ but don't know how to compare indexed characters from the same or different strings. Here's a palindrome example that takes an int and converts it to a string through a stringstream.

bool ispalindrome(int a) {
    stringstream stream;
    stream<<a;
    string str = stream.str();
    int length = str.length();
    int offset = length - 1;
    for (int i=0; i<=offset; i++ && offset--) {
        if (str[i] == str[i + offset]) {
            return false;
        }
        offset--;
    }
    return true;
}

For some reason this is always evaluated to false. I wouldn't think null termination would have anything to do with it because it's not reported by the length, so I guess I must be using the wrong comparison method. I can't seem to find something like strncmp but with single characters.

[Edit: fixed title]

Upvotes: 2

Views: 208

Answers (5)

pcodex
pcodex

Reputation: 1940

If it's just checking for a palindrome you could also use reverse from STL

#include <algorithm>
#include <string>

bool isPalinDrome = false;

std::string mystr = "cnc";
std::string mystrcpy = mystr;
std::reverse(mystrcpy.begin(),mystrcpy.end());
if(mystr == mystrcpy)
isPalindrome =  true;

But if you're just comparing individual characters then the answers above already tell you how to go about it. So just to reiterate, you need to only traverse halfway through the string either way

Upvotes: 0

David Fleury
David Fleury

Reputation: 94

May be the use of a comma,

for (int i=0; i<=offset; i++ ,offset--)

is more usual ?

Else,

if (str[i] == str[i + offset]) {

will be better with '!=' instead of '=='

But, with a simple sample, I don't see the 'always false' behavior

int main() {
  for ( int i = 0; i < 1000; ++i )
  cout << i << " = " << ispalindrome(i) << endl;
}

Upvotes: 1

dreamlax
dreamlax

Reputation: 95335

You could use iterators:

std::string::iterator start = str.begin();
std::string::reverse_iterator end = str.rbegin();

int halfWay = str.length() / 2;

for (int i = 0; i <= halfWay; i++, start++, end++)
{
    if (*start != *end)
        return false;
}

return true;

Disclaimer: untested, but also I'm not very good at C++!

Upvotes: 1

Luchian Grigore
Luchian Grigore

Reputation: 258608

I don't know how you wrote that loop, but I'm pretty sure it should be

for (int i=0; i<=offset; i++, offset--) {
    if (str[i] != str[offset]) {
        return false;
    }
}

Upvotes: 5

ecatmur
ecatmur

Reputation: 157354

Your checking condition should be:

    if (str[i] != str[i + offset]) {
               ^--here

Upvotes: 0

Related Questions