2

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?

iBug
  • 35,554
  • 7
  • 89
  • 134
Tyson B.
  • 31
  • 5
  • Use a loop until you can't find anymore. – iBug Dec 16 '17 at 06:26
  • 2
    Possible duplicate of [The most elegant way to iterate the words of a string](https://stackoverflow.com/questions/236129/the-most-elegant-way-to-iterate-the-words-of-a-string) – Austin Brunkhorst Dec 16 '17 at 06:26
  • @AustinBrunkhorst No, that's very different. We don't want every word here. Just where the one word can be located. – Galik Dec 16 '17 at 06:47

1 Answers1

2

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
iBug
  • 35,554
  • 7
  • 89
  • 134
  • @Galik Makes sense. Thanks for suggestion. – iBug Dec 16 '17 at 06:47
  • Setting pos += a.size() still causes an infinite loop. The while sets pos = 1 when found, and then it will hit pos += a.size(), which sets pos = 4, which doesn't get me anywhere! – Tyson B. Dec 16 '17 at 06:53
  • @TysonB. I'm not sure how you got to this point, but according to [CppReference](http://en.cppreference.com/w/cpp/string/basic_string/find), it should end reliably. – iBug Dec 16 '17 at 06:56
  • @TysonB. Whatever you think. I didn't meant to be aggressive. But next time please copy and paste from answers before reporting errors. – iBug Dec 16 '17 at 07:08
  • @TysonB. The while sets `pos` to the position of the search word if found. So you can guarantee to be able to add the length of the search word to `pos` because otherwise it would never have been found and the code to increment it would never have been called. – Galik Dec 16 '17 at 07:20