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?
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;
};
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With