std::string::find()无法将std::string用作参数

std::string::find() not working with std::string as argument

本文关键字:std string 参数 find      更新时间:2023-10-16

我在使用std::string::find()时遇到了一些对我来说没有多大意义的东西。我希望这里的人能够发现我的错误:

std::string testString = "PFAIL";
std::string response = "PFAILn";
if( response.find(testString) != std::string::npos )
{
    //do something
}

由于某种原因,此代码从未命中//do something注释。有什么想法吗?

编辑:我的意思是它永远不会到达//do something代码块,如果我用以下方式表达它,它应该这样做:

if( response.find( testString.c_str() ) != std::string::npos )
{
    // do something
}

也许您应该考虑在if语句中使用直接逻辑:

if( response.find(testString) == std::string::npos )

这个合乎逻辑的表达可能会减少你的困惑。如果find的返回值等于std::string::npos,则在response字符串中未找到testString变量中的字符串。

伊迪丝:我的逻辑回答错了。

您的情况与预期的情况不符。如果未找到任何内容,则返回npos。由于响应中明确包含测试,因此不会返回npos,并且会输入if的正文。