string count occurrences c++

To count the occurrences of a specific string in C++, you can follow these steps:

  1. Declare a string variable to store the input text.
  2. Declare another string variable to store the target substring you want to count.
  3. Use the find() function from the string library to search for the target substring within the input text.
  4. Initialize a count variable to keep track of the number of occurrences.
  5. Use a while loop to iterate through the input text until the find() function returns string::npos, indicating that the target substring was not found.
  6. Inside the loop, increment the count variable and update the starting position for the next search by adding the length of the target substring to the current position.
  7. After the loop ends, the count variable will hold the total number of occurrences of the target substring in the input text.

Here's an example code snippet that demonstrates these steps:

#include <iostream>
#include <string>

int main() {
    std::string inputText = "Hello world, hello universe, hello everyone!";
    std::string targetSubstring = "hello";

    size_t position = inputText.find(targetSubstring);
    int count = 0;

    while (position != std::string::npos) {
        count++;
        position = inputText.find(targetSubstring, position + targetSubstring.length());
    }

    std::cout << "Number of occurrences: " << count << std::endl;

    return 0;
}

In this example, the input text is "Hello world, hello universe, hello everyone!" and the target substring is "hello". The code uses the find() function to search for the target substring and increment the count variable each time it finds a match. Finally, it outputs the total number of occurrences, which in this case would be 3.