我使用一个简单的字符串函数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;
};
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句