繁体   English   中英

string.find()不返回-1

[英]string.find() doesn't return -1

下面的代码很简单。 据我所知,如果string :: find()找不到匹配项,则返回-1。 但是由于某些原因,下面的代码无法正常工作。 每次我运行这段代码,我都会无休止的循环。 谢谢你的帮助!

#include <string>
#include <iostream>
using namespace std;

int main()
{
    string text;
    text = "asdasd ijk asdasd";
    string toReplace = "ijk";
    cout<<text<<endl;
    int counter = 0;
    while ( text.find(toReplace) != -1)
        counter++;

    cout<<counter<<endl;

    system("pause");
}

除了完全正确的其他答案外,我只是想补充一点,无论如何,while循环将产生一个无限循环。 例如:

while(text.find(toReplace) != std::string::npos)
    counter++;

这将是一个无休止的循环,因为它将继续尝试在text查找toReplace字符串,并且始终会找到它(这是因为find每次都从字符串的开头开始)。 这可能不是您想要的。

如果未找到搜索的子字符串,则std::string::find返回std::string::npos ,而不是-1 npos的确切值是实现定义的,因此请使用npos ,如

while ( text.find(toReplace) != std::string::npos)

想一想,即使find想要, find也不会返回-1,因为find的返回类型指定为std::size_t ,这是无符号类型。

此外,无论调用多少次,find都会始终搜索该子字符串的第一个匹配项。 如果要遍历所有事件,则应使用find的重载,该重载带有第二个参数-从其开始搜索的位置。

无论是谁告诉您的,或者无论您在何处阅读,它都对您说谎。

如果std::string::find失败,则返回std::string::npos ,而不是-1

如果不确定,则应查看有关此类内容的文档。

因此,您的while将会是:

while ( std::string::npos != text.find(toReplace) )

关于您的评论:

更新:我试图使用while(text.find(toReplace)!= string :: npos),但我仍然遇到无尽的循环:( – user2167403 10秒前

您应该真正学会阅读文档 使用变量存储std::string::find的最后结果(不同于std::string::npos ),并使用std::string::find的第二个参数pos (通过传递值last_match_position + 1 )。

省略第二个参数std::string::find总是从字符串的开头开始,这将导致无限循环。

在代码段中,您提供的text变量包含子字符串“ ijk”,该子字符串存储在toReplace变量中。 只要在while循环中, texttoReplace变量均未更改,find方法将始终不返回-1值,这是while循环继续的条件。

正如其他注释中std::string::npos那样,您不应检查-1而是检查std::string::npos

确实有助于阅读手册页(答案是string :: npos)。

参见http://www.cplusplus.com/reference/string/string/find/

暂无
暂无

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

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