按字典顺序比较字符串

Comparing strings lexicographically(按字典顺序比较字符串)

本文介绍了按字典顺序比较字符串的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我认为如果我使用诸如>"和<"之类的运算符在 C++ 中比较字符串,这些会按字典顺序比较它们,问题是这有时只在我的计算机中有效.例如

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?

推荐答案

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

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";

这是 c++ 风格的解决方案.

This is the c++ style solution to that.

或者:

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

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

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";

将再次按预期工作.

编辑(感谢 churill 的评论):从 c++14 开始,您可以使用字符串文字:

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

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

这篇关于按字典顺序比较字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!

本文标题为:按字典顺序比较字符串

基础教程推荐