本文介绍了当使用== - 1时,string.find()返回true,当使用&lt; 0时返回false的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述 29岁程序员,3月因学历无情被辞! 我试图找到一个字符串内的字符,但我得到意想不到的结果。我的理解是,当它没有找到时, true 。 std :: string s =123456799; if(s.find('8')< 0) cout<< 未找到<< ENDL; else cout<< 找到<< ENDL; //输出:找到 但是,当使用 std :: string s =123456799 ; if(s.find('8')== -1) cout<< 未找到<< ENDL; else cout<< 找到<< ENDL; //输出:找不到 解决方案 这是不准确的。根据文档: 所以准确的说,当找不到 std :: string :: find 时,会返回 std :: string :: npos 。重点是 std :: string :: npos 的类型是 std :: string :: size_type ,是一个无符号整数类型。即使它是从 -1 的值初始化的,它不是 -1 ;它仍然没有签名。所以 s.find('8')将始终为 false ,因为不可能是负数。 std :: string :: npos : 所以你应该使用 std :: string :: npos 检查结果,避免这种混淆。 $ b如果(s.find('8')== std :: string :: npos) cout<< 未找到<< ENDL; else cout<< 找到<< ENDL; if(s。 find('8')== - 1)可以正常工作,因为 operator == 这里是没有签名的,右边的是签名的。根据算术运算符的规则, $ b否则,如果无符号操作数的转换等级大于或等于有符号操作数的转换等级,则将有符号操作数转换为 所以 -1 将被转换为无符号,这是 std :: string :: npos 的值,然后按预期工作。I am trying to find a character within a string but I am getting unexpected results. My understanding is that string::find(char c) returns -1 when it is not found. However, I am getting some unexpected results.Even though the string does not include an '8', it is still returning true.std::string s = "123456799";if(s.find('8')<0) cout << "Not Found" << endl;else cout << "Found" << endl;//Output: FoundHowever, when using == instead the code works as expected.std::string s = "123456799";if(s.find('8')==-1) cout << "Not Found" << endl;else cout << "Found" << endl;//Output: Not Found 解决方案 It's not accurate. According to the documentation:So to be precise, when not found std::string::find will return std::string::npos. The point is that the type of std::string::npos is std::string::size_type, which is an unsigned integer type. Even it's initialized from value of -1, it's not -1; it's still unsigned. So s.find('8')<0 will always be false because it's not possible to be negative.Documentation of std::string::npos:So you should use std::string::npos for checking the result, to avoid such kind of confusing.if (s.find('8') == std::string::npos) cout << "Not Found" << endl;else cout << "Found" << endl;if(s.find('8')==-1) works fine, because the left-hand operand of operator== here is unsigned, the right-hand one is signed. According to the rules for arithmetic operators, So -1 will be converted to unsigned, which is the value of std::string::npos and then all work as expected. 这篇关于当使用== - 1时,string.find()返回true,当使用&lt; 0时返回false的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持! 上岸,阿里云!
08-24 17:43
查看更多