C++ 查找给定字符串中所有子字符串的匹配项

C++ 查找给定字符串中所有子字符串的匹配项,c++,string,C++,String,我使用一个简单的字符串函数strstr来查找某个文本中第一个出现的字符串。我使用以下代码来计算文本中唯一单词的数量 for (int i = 0; i < 24; i++) { if (strstr(text, ops[i])) { op++; } } for(int i=0;i STRSTRESE()/Cyto>是C风格字符串,如果你真的使用C++,代码> STD::String 及其成员函数会更方便。 #include <strin

我使用一个简单的字符串函数
strstr
来查找某个文本中第一个出现的字符串。我使用以下代码来计算文本中唯一单词的数量

for (int i = 0; i < 24; i++) 
{
    if (strstr(text, ops[i])) 
    {
        op++;
    }
}
for(int i=0;i<24;i++)
{
if(strstr(文本,操作[i]))
{
op++;
}
}
但是我想找到程序中所有子字符串的出现。我如何做到这一点?

< p> <代码> STRSTRESE()/Cyto>是C风格字符串,如果你真的使用C++,<>代码> STD::String 及其成员函数会更方便。
#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;
};
#包括
#包括
使用名称空间std;
int main()
{
字符串s(“你好”);
整数计数=0;
size_t nPos=s.find(“hello”,0);//第一次出现
while(nPos!=字符串::nPos)
{
计数++;
nPos=s.find(“你好”,nPos+1);
}

cout您可以使用std::string find方法中的一种,这种方法更容易(也更安全),但是如果您确实需要使用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;
}
int-tmain(int-argc,_-TCHAR*argv[]
{           
const char test[]=“此测试是一个测试”;
常量字符subStr[]=“测试”;
const char*pccurrent=strstrstr(测试,subStr);
while(pCurrent!=NULL)
{

std::cout我会将要搜索的字符串存储在
string
变量中,删除第二个
find()
,并将第一个
find()
移动到循环中:
string sub=“hello”;size\t nPos=0;而((nPos=s.find(sub,nPos))!=string::nPos{count++;nPos+=sub.size()}