Reputation: 31
I'm currently trying to find a word inside a string. I'm using string::find()
. However this only finds the word in the string for one time.
string a = "Dog";
string b = "I have a dog, his name is dog";
if (b.find(a) != string::npos)
{
...
}
Is there a way to scan string b
to see how many times the word "dog" appears?
Upvotes: 2
Views: 1346
Reputation: 37217
Use a loop until you can't find anymore.
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
Upvotes: 2