#include <string>
#include <iostream>
#include <fstream>
using namespace std;
int search(string pat, string txt)
{
int M=(int)pat.length();
int N=(int)txt.length();
int occurences=0;
for (int s=0; s<=N-M; s++)
{
int j;
for (j=0; j<M; j++)
{
if (txt[s+j]!= pat[j])
break;
}
if (j==M)
{
occurences++;
}
}return occurences;
}
int main()
{
string pat;
string txt;
int line = 1;
cout << "Pattern: ";
cin >> pat;
cout << endl;
ifstream infile("/Users/irem/Library/Developer/Xcode/DerivedData/sample2.txt");
while (getline(infile, txt))
{
cout << "Line " << line << ": " << search(pat, txt) << " occurences" << endl;
line++;
}
return 0;
}
我的代码完全读取文件并在文本文件中搜索给定的字符串。但是我想要搜索函数进行字符串匹配时出现多少次出现的信息?行信息始终保持为1。