Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Comparing strings lexicographically

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?

like image 554
slugo Avatar asked Jan 12 '13 19:01

slugo


People also ask

What does it mean to compare strings lexicographically?

Two strings are lexicographically equal if they are the same length and contain the same characters in the same positions.

How do you compare two strings lexicographically in Python?

You can use ( > , < , <= , <= , == , != ) to compare two strings. Python compares string lexicographically i.e using ASCII value of the characters. Suppose you have str1 as "Mary" and str2 as "Mac" .

How do you find the lexicographic order of a string?

Approach: Find a string which is lexicographically greater than string S and check if it is smaller than string T, if yes print the string next else print “-1”. To find string, iterate the string S in the reverse order, if the last letter is not 'z', increase the letter by one (to move to next letter).


2 Answers

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"; 
like image 157
Ivaylo Strandjev Avatar answered Sep 21 '22 04:09

Ivaylo Strandjev


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.

like image 45
Brent Bradburn Avatar answered Sep 21 '22 04:09

Brent Bradburn