find all occurrences of a substring in a string c++

Sure! Here is an example of how you can find all occurrences of a substring in a string in C++:

#include <iostream>
#include <string>

int main() {
    std::string str = "Hello, hello, how are you?";
    std::string substring = "hello";

    size_t position = str.find(substring);
    while (position != std::string::npos) {
        std::cout << "Substring found at position: " << position << std::endl;
        position = str.find(substring, position + 1);
    }

    return 0;
}

In this code, we start by including the necessary headers <iostream> and <string>.

Next, we define our main function.

Inside the main function, we declare a string variable str and initialize it with the string we want to search in.

Then, we declare another string variable substring and initialize it with the substring we want to find occurrences of.

We use the find function of the string class to find the first occurrence of the substring in the string. The find function returns the position of the first occurrence of the substring, or std::string::npos if the substring is not found.

We enter a while loop that continues as long as the substring is found. Inside the loop, we print the position of the substring using std::cout.

We then update the position by searching for the substring starting from the next position in the string, by passing position + 1 as the second argument to the find function.

Finally, we return 0 to indicate successful execution of the program.

This code will output:

Substring found at position: 7
Substring found at position: 14

which are the positions of the occurrences of the substring "hello" in the string "Hello, hello, how are you?".

I hope this helps! Let me know if you have any further questions.