Sparrow
Sparrow

Reputation: 305

Find occurrences of all substrings in a given string

I use a simple string function strstr to find the first occurrence of a string in some text. I used the following code to count the number of unique words in a text.

for (int i = 0; i < 24; i++) 
{
    if (strstr(text, ops[i])) 
    {
        op++;
    }
}

But I want to find the occurrence of all the sub strings in the program. How can I do this?

Upvotes: 3

Views: 26199

Answers (2)

jfly
jfly

Reputation: 8010

strstr() is for the C-style string, if you are really using C++, std::string and its member function would be much more convenient.

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

Upvotes: 10

acarlon
acarlon

Reputation: 17272

You can use one of the std::string find methods which would be easier (and safer), but if you really need to use strstr:

int _tmain(int argc, _TCHAR* argv[])
{           
    const char test[] = "this test is a test";
    const char subStr[] = "test";
    const char* pCurrent = strstr( test, subStr );
    while( pCurrent != NULL )
    {
        std::cout << "found" << std::endl;
        pCurrent++;
        pCurrent = strstr( pCurrent, subStr );
   }
   return 0;
}

This just increments the point where the last sub string was found. Note that you should do the normal string length, NULL and safety checks.

Upvotes: 3

Related Questions