分享纯C语言英汉字典源码

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

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

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

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


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

  快速模式匹配---KMP算法
  
**************************/
#include <stdio.h>

#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");
}


测试数据:

good好的
hi你好


  • 2
    点赞
  • 10
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值