两文件之间的字符串匹配

#include 
#include 
#include 
#include 
using namespace std;

const int N = 1e5 + 10, M = 1e6 + 10;

char buffs[N], buffp[N], p[N], s[M];
int n, m;
int ne[N];

void delete_char(char *str, char target)
{
    int i, j;
    for (i = 0, j = 0; str[i] != ''; ++ i)
    {
        if (str[i] != target)    str[j ++] = str[i];
    }
    str[j] = '';
}

bool KMP(char *s, char *p)
{
    ne[0] = -1;
    for (int i = 1, j = -1; i < n; ++ i)
    {
        while (j != -1 && p[i] != p[j + 1])    j = ne[j];
        if (p[i] == p[j + 1])    j ++;
        ne[i] = j;
    }
    
    for (int i = 0, j = -1; i < m; ++ i)
    {
        while (j != -1 && s[i] != p[j + 1])    j = ne[j];
        if (s[i] == p[j + 1])    j ++;
        if (j == n - 1)
        {
            return true;
//            cout << i - j << " ";
//            j = ne[j];
        }
    }
    return false;
}

int main()
{
    cout << "核查结果如下:" << endl;
    
    FILE *fp;
    
    // 读取模式串s 
    if ((fp = fopen("E://全体名单.txt", "r")) == NULL)
    {
        printf("文件打开错误
");
        exit(0);
    }
    
    while (!feof(fp))
    {
        fgets(buffs, sizeof(buffs), fp);
        strcat(s, buffs);
    }
    
    m = strlen(s);
    delete_char(s, '
');
//    printf("%s
", s);
    
    // 读取模板串p 
    if ((fp = fopen("E://登记名单.txt", "r")) == NULL)
    {
        printf("文件打开错误
");
        exit(0);
    }
    
    while (!feof(fp))
    {
        fgets(buffp, sizeof(buffp), fp);
        delete_char(buffp, '
');
//        printf("%s
", buffp);
        n = strlen(buffp);
        if (KMP(s, buffp))
            cout << buffp << " " << "已接种" << endl;
        else
            cout << buffp << " " << "未接种" << endl;
    }
        
    return 0;
}

原文地址:https://www.cnblogs.com/mjn1/p/15017089.html