文学研究助手(实践作业)kmp算法查询单词

点个赞吧大佬们!!!💕💕💕

#include<bits/stdc++.h>
//#include<iostream>
//#include<cstdlib>
//#include<istream>
using namespace std;

char* Read(char ch[])//从指定文件存入字符到word里
{
    char* word = (char*)calloc(2000, sizeof(char));//分配空间分配后自动初始化为0
    int i = 0;
    ifstream txt(ch);//打开括号内的文件
    if (!txt)
    {
        cout << "打开文件错误" << ch << endl;
        return 0;
    }
    txt >> noskipws;//设置读取空白字符
    while (!txt.eof())//当没有接收到文件结尾时一直执行
    {
        txt >> word[i++];//读取字符到数组中
    }
    txt >> skipws;//恢复设置不读取空格
    txt.close();//清空
    return word;
}

void GetWord(char t[], int next[])
{// 求模式串T的next函数值并存入数组next
    
    int j = 0, k = -1;
    int n = strlen(t);
    next[j] = -1;
    while (j < n)//求数组是否有重复
    {
        if (k == -1 || t[j] == t[k])
        {
            j++; k++; next[j] = k;
        }
        else k = next[k];
    }
}
int IndexKMP(char s[], char t[], int next[])
{// 利用模式串T的next函数求T在主串S中第pos个字符之后的位置的KMP算法。
    // 其中,T非空,1≤pos≤StrLength(S)
    int i, j;
    i = 0; j = 0;
    int count = 0;    //计数器
    int m = strlen(s), n = strlen(t);
    while (i < m && j < n)   // 
    {
        if (j == -1 || s[i] == t[j])
        {
            i++; j++;
        }              // 如果相同则会继续比较后继字符
         else j = next[j];// 模式串向右移动
        if (j >= n)
        {
            count++;
            cout << "单词第" << count << "次出现在" << (i - j + 1) / 84 + 1 << "行,第" << (i - j + 1) << "个字符开始" << endl;
            j = 0;  //J必须重新赋值为零,
        }// 匹配成功
    }
    return count;
}
int main()
{
    char location[10] = { 0 },word[10], * ch;//location文件位置,word查询单词
    int *next, wordl,n;
    cout << "请输入小说文件路径" << endl;
    cin >> location;
    ch = Read(location);//将文件位置的地址存放
    cout << ch << endl;
    cout << "请输入要查询的单词:";
    cin >> word;
    wordl = strlen(word);//求字符长度
    next = new int[wordl];//创建一个长度为word的数组
    GetWord(word, next);//求next
    n = IndexKMP(ch, word,next);//查询
    cout << word << "在小说中总共出现" << n << "次" << endl;

    exit(0);
    return 0;

}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值