我有:
#include <iostream>
#include <string>
int main(int argc, const char * argv[])
{
std::string foo = "<!";
if (foo.find("<")) {
std::cout<<"Found";
}
return 0;
}
为什么这段代码找不到 "<"
?
如果我将行更改为 foo.find("!")
,然后找到。那么"<"
有什么问题呢? ?
最佳答案
如果成功 std::string::find()
返回找到其参数的索引,而不是 bool 值。
因为 "<"
在索引 0 处找到它返回 0,并且在 bool 上下文中 0 为假,因此条件失败。因为"!"
在索引 1 处返回 1,并且在 bool 上下文中为真。
而不是测试是否find
返回 true 你需要使用:
if (foo.find("<") != std::string::npos) {
npos
是保留的特殊值,表示“不是位置”和 find
返回它表示未找到该值。
注意当你想搜索单个字符时,最好这样做,而不是搜索长度为 1 的字符串,即使用 foo.find('<')
而不是 foo.find("<")
您可以通过尝试搜索 '<'
来自行调试它在字符串 "!<"
中你会发现结果与你搜索的特定字符无关,而只与它在字符串中找到的位置有关。
关于c++ - 为什么 std::string.find() 不能用于 "<"?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25911533/