我使用一个简单的字符串函数 strstr
来查找某个字符串在某些文本中的第一次出现。我使用以下代码来计算文本中唯一单词的数量。
for (int i = 0; i < 24; i++)
{
if (strstr(text, ops[i]))
{
op++;
}
}
但是我想找出程序中所有子串的出现。我该怎么做?
最佳答案
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;
};
关于c++ - 查找给定字符串中所有子字符串的出现,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22315738/