/**************************************************************** --程序描述: 上机实验3.doc(有描述) --修改记录: 从前写的代码不够规范——2009.6.17 --修改人: 吴强 --输入要求: 无 ****************************************************************/ #include #include #include const int MAX=120; //一行能容最大字符数 //保留字信息结构 struct ResWord { char str[30]; //保留字 int count; //记录出现次数 std::list iList; //出现次序的行号 }; //KMP匹配算法 void Kmp_next(char *t, int next[]) { int i = 0; int j = 0; next[0] = 0; while(i < strlen(t)) { if (j==0 || t[i] == t[j-1]) { ++i; ++j; next[i]=j; } else { j=next[j-1]; } } } int Kmp(char *str, struct ResWord &s, int next[]) { int i=1; int j = 1; int cot = 0; while(i <= strlen(str)) { if (j == 0 || str[i-1] == s.str[j-1]) { ++i; ++j; } else { j = next[j-1]; } if (j > strlen(s.str)) //如果匹配成功 { cot++; j = 1; } } if (cot) { s.count += cot; return cot; } else { return 0; } } void main() { char fdata[MAX]; //用于保存文件一行的数据 int row = 1; //当前行号,当前行长度,保留字长度 int fdLen = 0; int rwLen = 0; struct ResWord rWord; std::ifstream Efile; std::ifstream Cfile; Efile.open("MatchStr.cpp"); Cfile.open("C++Word.txt"); rWord.count = 0; while(!Cfile.eof()) { char ch; Cfile.get(ch); if (Cfile.eof()) { break; } if ((ch >= 'a' && ch <= 'z') || (ch >= 'A' && ch <= 'Z') || '_' == ch) { rWord.str[rwLen++] = ch; } else if (rwLen != 0) { rWord.str[rwLen] = '/0'; //找出一个保留字 while(!Efile.eof()) { Efile.get(ch); if (Efile.eof()) { break; } if (ch != '/n') { fdata[fdLen++] = ch; //查找一行的字符 } else { row++; if (fdLen != 0) //逐行比较 { fdata[fdLen] = '/0'; //提取一行数据 //KMP算法的next地址 int *k_next = new int[strlen(fdata)]; Kmp_next(fdata, k_next); //如果该行有匹配成功,则加入该行号 if (Kmp(fdata, rWord, k_next)) { rWord.iList.push_back(row); } } else { continue; //跳过空行 } fdLen = 0; } } //输出当前关键字的信息 cout<< rWord.str<< ' '<< rWord.count<< ' '; std::list::iterator iter; iter = rWord.iList.begin(); while(iter != rWord.iList.end()) { cout<< *iter<< '-'; iter++; } cout<< endl; rWord.iList.clear(); rWord.count = 0; //出现次数清0 rwLen = 0; //查找保留字的下标回滚到0 row = 0; //文件流指针指向文件头部 Efile.clear(); Efile.seekg(0); } else { continue; //跳过两单词间的字符... } } Cfile.close(); Efile.close(); }
串的应用
最新推荐文章于 2023-04-29 21:07:02 发布