how to find a substring in a string in c++ from starting code example

Example 1: c++ check substring

if (s1.find(s2) != std::string::npos) {
    std::cout << "found!" << '\n';
}

Example 2: find all occurrences of a substring in a string c++

#include <string>
#include <iostream>

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;
};

Tags:

Cpp Example