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

时间:2017-12-16 06:24:33

标签: 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,看看#34; dog"出现?

1 个答案:

答案 0 :(得分:2)

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

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
相关问题