C++实现文学研究助手

Linux大全评论732 views阅读模式

文学研究助手的实现

设计目的:

1. 熟悉串类型的实现方法和文本匹配方法。

2. 熟悉一般文字处理软件的设计方法。

设计内容:

文学研究人员需要统计某篇英文小说中某些形容词的出现次数和位置。试写一个实现这

一目标的文字统计系统,称为“文学研究助手”。

设计要求:

1. 英文小说存于一个文本文件中。

2. 待统计的词汇集合要一次输入完毕。

3. 程序的输出结果是每个词的出现次数和出现位置所在行的行号,格式

自行设计。

源代码

#include<iostream>
#include<cstdlib>
#include<fstream>

using namespace std;

char *FileRead(char ch[])  //读文件函数
{
    char *c = (char *)calloc(2000, sizeof(char));  //calloc分配出来的内存,返回值也是void * 但是分配的内存是被清空过的,更安全
    int i = 0;
    ifstream in(ch);
    if (!in) { cout << "不能打开文件" << ch << endl; return 0; }
    in >> noskipws;  //读文件不跳过空格
    while (!in.eof())    //eof  判断是否读到文件尾
    {
        in >> c[i++];
    }
    in.close();
    return c;
}

void GetNext(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;
}

void ShowMenu()
{
    cout << "********************************************" << endl;
    cout << "******      文 学 研 究 助 手        ******" << endl;
    cout << "******      0.安全退出系统          ******" << endl;
    cout << "******      1.文件读入小说          ******" << endl;
    cout << "******      2.输出小说文本          ******" << endl;
    cout << "******      3.查询小说关键字        ******" << endl;
    cout << "\n\t\n\t\t请选择:";
}

企鹅博客
  • 本文由 发表于 2019年9月8日 20:21:28
  • 转载请务必保留本文链接:https://www.qieseo.com/134839.html

发表评论