cpp string find all occurence

#include <iostream>
#include <string>

int main() {
    std::string str = "Hello, hello, hello, how low?";
    std::string toFind = "hello";

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

    return 0;
}

Explanation for each step:

  1. #include <iostream> and #include <string>: Include necessary libraries for input/output and string operations in C++.

  2. int main() {: Beginning of the main function, the entry point of the C++ program.

  3. std::string str = "Hello, hello, hello, how low?";: Declares a string variable str and initializes it with a string containing multiple occurrences of the word "hello".

  4. std::string toFind = "hello";: Declares a string variable toFind which holds the substring to search for within the str string.

  5. size_t pos = str.find(toFind);: Uses the find function of the std::string class to search for the first occurrence of the substring toFind within the str string. The position of the first occurrence (if found) is stored in the pos variable.

  6. while (pos != std::string::npos) {: Enters a while loop that continues as long as the pos variable stores a valid position (i.e., not equal to std::string::npos, which signifies that the substring was not found).

  7. std::cout << "Substring found at position: " << pos << std::endl;: Outputs the position (pos) where the substring toFind was found within the str string.

  8. pos = str.find(toFind, pos + toFind.size());: Updates the pos variable by searching for the next occurrence of the substring toFind in str, starting the search from the position after the previously found occurrence (pos + toFind.size()).

  9. return 0;: Indicates successful completion of the main() function and the program, returning 0 to the operating system.