设为首页 加入收藏

TOP

分享纯C语言英汉字典源码
2014-11-24 00:11:54 来源: 作者: 【 】 浏览:17
Tags:分享 语言 英汉 字典 源码

近期深受开源的精神影响,并为之深深感动,想了很久,今天把我代码积累多年的一个“英汉字典”公布。

研一的时候因为无聊或者因为兴趣,做了一个纯C语言的英汉字典。核心算法是KMP快速查找算法,虽然有点长,但思想简单(我崇尚简单),基本思想为:当你输入某个英文时,如果字典收录了这个英文,会查出中文意思;如果没有收录,会提醒你输入中文意思。

做的时间比较久了,现在运行起来不是原本的意思,有空我会慢慢改进。

若你有心可以在此基础上改进,也可以告诉我哪里可以改进。谢谢!

view plain

/**************************

快速模式匹配---KMP算法

**************************/

#include

#define MAXSIZE 10000

typedef struct

{

char ch[MAXSIZE];

int length;

}Seqstr;

void Getnext(Seqstr p, int next[]);

void Kmp(Seqstr t, Seqstr p, int next[]);

void InputStr(Seqstr &str);

void OutputStr(Seqstr &str);

void FileToStr(FILE *fp, Seqstr &t);

int main(void)

{

int next[30];

FILE *fp;

Seqstr p, t;

p.length = 0;

t.length = 0;

InputStr(p);

OutputStr(p);

fp = fopen("word.txt", "r"); //InputStr(t);

if (fp != NULL)

{

FileToStr(fp, t);

fclose(fp);

OutputStr(t);

Getnext(p, next);

Kmp(t, p, next);

}

else

{

printf("can't open file!\n");

}

return 0;

}

void FileToStr(FILE *fp, Seqstr &str)

{

printf("input string from file...\n");

while (!feof(fp))

{

str.ch[str.length] = fgetc(fp);

str.length++;

}

str.ch[str.length] = '\0';

}

void InputStr(Seqstr &str)

{

char c;

printf("input a string:");

while((c = getchar()) != '\n')

{

str.ch[str.length] = c;

str.length++;

}

str.ch[str.length] = '\0';

}

void OutputStr(Seqstr &str)

{

int i = 0;

while(str.ch[i] != '\0')

{

printf("%c", str.ch[i]);

i++;

}

printf("\n");

}

void Kmp(Seqstr t, Seqstr p, int next[])

{

int i, j;

int appearTimes = 0;

int lines = 1;

i = 0;

j = 0;

while(i < t.length)

{

while (i < t.length && j < p.length)

{

if (j == -1 || t.ch[i] ==p.ch[j])

{

i++;

j++;

}

else

{

j = next[j];

}

if (t.ch[i] == '\n') //计算行数

{

lines++;

i++;

}

}//while

if(j == p.length) //首次出现的位置(return i-p.length)

{

appearTimes++;

printf("The %d times appear at line: %d\n", appearTimes, lines);

j = 0;

}

}//while

}

void Getnext(Seqstr p, int next[])

{

int i, j;

next[0] = -1;

i = 0;

j = -1;

while(i < p.length)

{

if(j == -1 || p.ch[i] == p.ch[j])

{

++i;

++j;

next[i] = j;

}

else

{

j = next[j];

}

}

for(i = 0; i < p.length; i++)

{

printf("next[%d] = %3d\n", i, next[i]);

}

printf("\n");

}

测试数据:

view plain

good好的

hi你好

摘自 邓秀茂的博客

】【打印繁体】【投稿】【收藏】 【推荐】【举报】【评论】 【关闭】 【返回顶部
分享到: 
上一篇函数指针模板 下一篇排序组合,AS实现穷举算法

评论

帐  号: 密码: (新用户注册)
验 证 码:
表  情:
内  容: