Warning: file_get_contents(/data/phpspider/zhask/data//catemap/6/cplusplus/142.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C++ C++;多次在字符串中查找单词_C++_String_Parsing - Fatal编程技术网

C++ C++;多次在字符串中查找单词

C++ C++;多次在字符串中查找单词,c++,string,parsing,C++,String,Parsing,我目前正试图在字符串中找到一个单词。我正在使用string::find()。但是,这只能在字符串中查找一次单词 string a = "Dog"; string b = "I have a dog, his name is dog"; if (b.find(a) != string::npos) { ... } 有没有办法扫描字符串b以查看单词“dog”出现了多少次?使用循环,直到找不到为止 std::size_t count = 0, pos = 0; while ((pos =

我目前正试图在字符串中找到一个单词。我正在使用
string::find()
。但是,这只能在字符串中查找一次单词

string a = "Dog";
string b = "I have a dog, his name is dog";

if (b.find(a) != string::npos)
{
    ...
}

有没有办法扫描字符串
b
以查看单词“dog”出现了多少次?

使用循环,直到找不到为止

std::size_t count = 0, pos = 0;
while ((pos = b.find(a, pos)) != std::string::npos) {
    pos += a.size(); // Make sure the current one is skipped
    count++;
}
// Now you have count

使用循环直到你找不到为止。可能是@AustinBrunkhorst的重复。不,这是非常不同的。我们不想听到这里的每一个字。“这一个词就在哪里。”加利克说得通。谢谢你的建议。设置pos+=a.size()仍然会导致无限循环。while在找到时设置pos=1,然后它将点击pos+=a.size(),这将设置pos=4,这不会让我有任何进展@泰森布。“我不知道你是怎么做到这一点的,但据我所知,它应该可靠地结束了。”泰森布。不管你怎么想。我并不是有意挑衅的。但下次请在报告错误之前复制并粘贴答案。@TysonB。while将
pos
设置为搜索词(如果找到)的位置。因此,您可以保证能够将搜索词的长度添加到
pos
,因为否则将永远不会找到它,并且将永远不会调用增加它的代码。