C++ 按字典序比较字符串

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/14297185/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-27 18:11:44  来源:igfitidea点击:

Comparing strings lexicographically

c++stringcompare

提问by slugo

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

我想如果我在 c++ 中使用诸如“>”和“<”之类的运算符来比较字符串,它们会按字典顺序比较它们,问题是这只在我的计算机中有时有效。例如

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?

这将打印“是”,为什么会发生这种情况?或者我应该使用其他方法来按字典顺序比较字符串吗?

回答by Ivaylo Strandjev

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

std::string像这样比较-s起作用。但是,您正在比较字符串文字。要进行比较,您需要使用它们初始化 std::string 或使用 strcmp:

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

This is the c++ style solution to that.

这是 C++ 风格的解决方案。

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:

编辑(感谢 Konrad Rudolph 的评论):实际上,在第一个版本中,只有一个操作数应该显式转换,因此:

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

Will again work as expected.

将再次按预期工作。

回答by nobar

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

您正在比较类型为 的“原始”字符串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.

@izomorphius 提出了一些很好的解决方案。