cpp string find all occurence 1

cpp string find all occurence

#include 
#include 

using namespace std;

int main()
{
    string s("hello hello");
    int count = 0;
    size_t nPos = s.find("hello", 0); // first occurrence
    while(nPos != string::npos)
    {
        count++;
        nPos = s.find("hello", nPos + 1);
    }

    cout << count;
};

Here is what the above code is Doing:
1. We're using the find() function to find the first occurrence of the word "hello" in the string.
2. If the word is found, we're incrementing the count variable.
3. We're then using the find() function again to find the next occurrence of the word "hello" in the string.
4. We're repeating the above steps until the word is not found.

Similar Posts