简体   繁体   English

无论情况如何,字符串比较的Less Than运算符都会产生相同的结果

[英]Less Than operator on string comparison yields same result no matter the situation

I wanted to see if the Less Than operator ( < ) would work on strings. 我想看看Less Than运算符( < )是否适用于字符串。 Well, it did. 嗯,确实如此。 I started to experiment with it, and it turns out, I got the same result, regardless of the situtaion. 我开始尝试它,事实证明,无论坐姿如何,我都得到了相同的结果。 The string on the left is always less than the string on the right, even if I swap the strings. 左边的字符串总是小于右边的字符串,即使我交换了字符串。 Curious on why it did this, I tried to look up what the < operator actually does for strings. 好奇为什么会这样做,我试着查看<操作符实际上对字符串的作用。 I read that it does a lexicographical comparison of the two strings. 我读到它对两个字符串进行了字典比较。 Still, this did not answer why my code was doing what it was doing. 尽管如此,这并没有回答为什么我的代码正在做它正在做的事情。 For example: 例如:

int main () {

if ("A" < "B")
    std::cout << "Yes";
else
    std::cout << "No";

return 0;

}

It would output Yes . 它会输出Yes That makes sense. 那讲得通。 But when I swap the strings: 但是当我交换字符串时:

int main () {

if ("B" < "A")
    std::cout << "Yes";
else
    std::cout << "No";

return 0;

}

It would still output Yes . 它仍然会输出Yes I don't know if I am just being ignorant right now and not fully understanding what is happening here, or if there is something wrong. 我不知道我现在是否只是无知而且不完全了解这里发生的事情,或者是否有什么问题。

It's because a string literal gives you a pointer to a read-only array containing the string (plus its terminator). 这是因为字符串文字为您提供了指向包含字符串(以及其终结符)的只读数组的指针。 What you are comparing are not the strings but the pointers to these strings. 你比较的不是字符串而是指向这些字符串的指针

Use std::strcmp if you want to compare C-style strings. 如果要比较C风格的字符串,请使用std::strcmp Or use std::string which have overloaded comparison operators defined. 或者使用std::string ,它定义了重载的比较运算符。

You are comparing the pointer to the string "A" with the pointer to the string "B". 您正在将指向字符串“A”的指针与指向字符串“B”的指针进行比较。

If you want to compare just the value in the chars then use the single quote 'A' and 'B', if you want to compare strings then use the std::string class std::string("A") < std::string("B") or strcmp() 如果你只想比较字符中的值,那么使用单引号'A'和'B',如果你想比较字符串,那么使用std :: string类std::string("A") < std::string("B")或strcmp()

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM