Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Find occurrences of all substrings in a given string

Tags:

c++

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?

like image 589
Sparrow Avatar asked Jan 26 '26 17:01

Sparrow


2 Answers

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;
};
like image 144
jfly Avatar answered Jan 29 '26 08:01

jfly


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.

like image 29
acarlon Avatar answered Jan 29 '26 09:01

acarlon



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!