C++ str.find()似乎忽略了字符串中的第一个字符
在包含完整代码的应用程序中C++ str.find()似乎忽略了字符串中的第一个字符,c++,C++,在包含完整代码的应用程序中 #include <iostream> #include <string> using namespace std; int main() { string str = "Insert"; int kint = 0; if (kint == 0 && str.find("Insert")) { cout << "found" << endl;
#include <iostream>
#include <string>
using namespace std;
int main()
{
string str = "Insert";
int kint = 0;
if (kint == 0 && str.find("Insert"))
{
cout << "found" << endl;
}
return 0;
}
#包括
#包括
使用名称空间std;
int main()
{
string str=“插入”;
int-kint=0;
如果(kint==0&&str.find(“插入”))
{
cout您忽略了一个事实,即当find
不返回任何内容时,它返回的npos
不是零。返回值0表示它在索引0中找到了它要查找的内容
if (kint == 0 && str.find("Insert) != string::npos) { ... }
[注意:在大约15秒钟的时间里,这个答案错误地宣称,str.find()
在失败时返回str.end()
。这是垃圾。如果有人阅读了错误的版本并相信它,我深表歉意。]您缺少一个事实,即当find
不返回任何内容时,它返回的npos
不是零。返回值0表示它在索引0中找到了它要查找的内容
if (kint == 0 && str.find("Insert) != string::npos) { ... }
[注意:在大约15秒钟的时间里,这个答案错误地宣称,str.find()
在失败时返回str.end()
。这是垃圾。如果有人阅读了错误的版本并相信了它,我深表歉意。]看看find函数返回了什么:
返回值第一个的位置
事件的字符串中出现
已搜索内容。如果内容为
未找到,成员值npos为
返回
由于搜索“Insert”,它返回0,而if失败,请查看find函数返回的内容:
返回值第一个的位置
事件的字符串中出现
已搜索内容。如果内容为
未找到,成员值npos为
返回
由于搜索“插入”,它返回0,如果失败,它实际上返回位置,在您的情况下为0。0转换为false。。。
看
您需要检查if语句中的str.find(“Insert”)!=std::string::npos
,实际上它返回位置,在您的情况下为0。0转换为false。。。
看
您需要在if语句中检查str.find(“Insert”)!=std::string::npos
find()返回找到的字符的位置。因此,第一个字符的位置为0,在布尔值中转换为false。
你应该和非营利组织比较
if (kint == 0 && str.find("Insert") != str::npos)
{
cout << "found" << endl;
}
if(kint==0&&str.find(“插入”)!=str::npos)
{
coutfind()返回找到的字符的位置。因此,第一个字符的位置为0,在布尔值中转换为false。
你应该和非营利组织比较
if (kint == 0 && str.find("Insert") != str::npos)
{
cout << "found" << endl;
}
if(kint==0&&str.find(“插入”)!=str::npos)
{
库特