我使用一个简单的字符串函数strstr来查找文本中第一次出现刺痛.我使用以下代码来计算文本中唯一单词的数量.
for(int i=0;i<24;i++)
{
if(strstr(text,ops[i]))
{
op++;
}
}
Run Code Online (Sandbox Code Playgroud)
但我想找到程序中所有子字符串的出现.我可以在JAVA中轻松完成.但我被要求用C++做这件事.有帮助吗?
strstr()对于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;
};
Run Code Online (Sandbox Code Playgroud)