题目三:文本文件单词的检索与计数

代码

#define _CRT_SECURE_NO_WARNINGS
#include<stdio.h>
#include<string.h>
#include<Windows.h>
#define BUF_SIZE 256
typedef struct seqstring {
	char string[100];
	int length;
}seqstring;
 
void getnext(seqstring p, int next[]) {
	int i, j;
	i = 0;
	j = -1;
	next[i] = j;
	while (i < p.length) {
		if (j == -1 || p.string[i] == p.string[j]) {
			next[++i] = ++j;
		}
		else {
			j = next[j];
		}
	}
	for (i = 0;i < p.length;i++) {
		printf("%d ", next[i]);
	}
}
int kmp(seqstring t, seqstring p, int next[]) {
	int i, j;
	i = j = 0;
	while (i < t.length && j < p.length) {
		if (j == -1 || t.string[i] == p.string[j]) {
			i++;j++;
		}
		else {
			j = next[j];
		}
	}
	if (j == p.length) return i - p.length;
	else return -1;
}
int  main() {
	seqstring t, p;
	int next[50];
	DWORD	nIn;
    char buffer[BUF_SIZE] = "";
   HANDLE handle = CreateFile("test.txt",
		GENERIC_READ,
		FILE_SHARE_READ,
		NULL,
		OPEN_EXISTING,
		FILE_ATTRIBUTE_NORMAL,
		NULL);
	if (handle == INVALID_HANDLE_VALUE) {
		printf("%d", GetLastError());
		return -1;
	}
	ReadFile(handle, buffer, BUF_SIZE, &nIn, NULL) ;
	strcpy(t.string, buffer);
	printf("%s\n", t.string);
	t.length = strlen(t.string);
 
	printf("please input string p:");
	scanf("%s", p.string);
	printf("%s\n", p.string);
	p.length = strlen(p.string);
	printf("next:");
	getnext(p, next);
	printf("\n%d\n", kmp(t, p, next));
}

你可能感兴趣的:(题目三:文本文件单词的检索与计数)