29

I thought that if I used operators such as ">" and "<" in c++ to compare strings, these would compare them lexicographically, the problem is that this only works sometimes in my computer. For example

if("aa" > "bz") cout<<"Yes";

This will print nothing, and thats what I need, but If I type

if("aa" > "bzaa") cout<<"Yes";

This will print "Yes", why is this happening? Or is there some other way I should use to compare strings lexicographically?

Ionică Bizău
  • 109,027
  • 88
  • 289
  • 474
slugo
  • 1,019
  • 2
  • 11
  • 22
  • 11
    The problem is that "aa" and "bz" are not *string* s. It's time to tell tutorial authors and teachers to call *the thing between the ""* as "textual literal" and not "string". It will remove the most of confusion and headache in newbies! – Emilio Garavaglia Jan 12 '13 at 21:36

3 Answers3

40

Comparing std::string -s like that will work. However you are comparing string literals. To do the comparison you want either initialize a std::string with them or use strcmp:

if(std::string("aa") > std::string("bz")) cout<<"Yes";

This is the c++ style solution to that.

Or alternatively:

if(strcmp("aa", "bz") > 0) cout<<"Yes";

EDIT(thanks to Konrad Rudolph's comment): in fact in the first version only one of the operands should be converted explicitly so:

if(std::string("aa") > "bz") cout<<"Yes";

Will again work as expected.

EDIT(thanks to churill's comment): since c++14 you can use string literals:

if("aa"s > "bz") cout<<"Yes";
Ivaylo Strandjev
  • 69,226
  • 18
  • 123
  • 176
7

You are comparing "primitive" strings, which are of type char const *.

The following is essentially equivalent to your example:

char const * s1 = "aa";
char const * s2 = "bz";
if ( s1 > s2 ) cout<<"Yes";

This is comparing the pointers (the memory addresses of the strings), not the contents.

@izomorphius has suggested some good solutions.

Brent Bradburn
  • 51,587
  • 17
  • 154
  • 173
0

You can use strcmp() function which is included in the #include <cstring> header file. strcmp() compares the two strings character by character. The process will continue until it reaches NULL or one of the strings become unequal (characters become unequal). For example:

#include <iostream>
#include <cstring>


void display(char *lhs, char *rhs, int result)
{
    if(result > 0)
        std::cout << rhs << " precedes " << lhs << std::endl;
    else if (result < 0)
        std::cout << lhs << " precedes " << rhs << std::endl;
    else
        std::cout << lhs << " and " << rhs << " are same" << std::endl;
}

int main()
{
    char lhs[] = "aa";
    char rhs[] = "bz";
    int result;

    result = strcmp(lhs,rhs);
    display(lhs,rhs,result);

    result = strcmp(lhs,lhs);
    display(lhs,lhs,result);

    return 0;
}

Output:

aa precedes bz
aa and aa are same
Geno C
  • 1,401
  • 3
  • 11
  • 26