Comparing strings lexicographically

会有一股神秘感。 提交于 2019-12-17 16:32:34

问题


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?


回答1:


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.




回答2:


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.



来源:https://stackoverflow.com/questions/14297185/comparing-strings-lexicographically

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!