串的应用

/****************************************************************
--程序描述:	上机实验3.doc(有描述)
--修改记录:	从前写的代码不够规范——2009.6.17
--修改人:	吴强	
--输入要求:	无
****************************************************************/

#include 
#include 
#include 

const int MAX=120;	//一行能容最大字符数

//保留字信息结构
struct ResWord
{
	char str[30];		//保留字
	int count;		//记录出现次数
	std::list iList;	//出现次序的行号
};

//KMP匹配算法
void Kmp_next(char *t, int next[])
{
	int i = 0;
	int j = 0;
	next[0] = 0;

	while(i < strlen(t))
	{
	   if (j==0 || t[i] == t[j-1])
	   {
	   	  ++i;
		  ++j;
	   	  next[i]=j;
	   }
	   else 
	   {
		   j=next[j-1];
	   }
	}
}

int Kmp(char *str, struct ResWord &s, int next[])
{
	int i=1;
	int j = 1;
	int cot = 0;

	while(i <= strlen(str))	
	{
		if (j == 0 || str[i-1] == s.str[j-1])
		{
			++i;
			++j;
		}
		else 
		{
			j = next[j-1];
		}

		if (j > strlen(s.str))		//如果匹配成功
		{
			cot++;
			j = 1;
		}
	}

	if (cot)
	{
		s.count += cot;
		return cot;
	}
	else 
	{
		return 0;
	}
}

void main()
{
	char	fdata[MAX];		//用于保存文件一行的数据
	int	row = 1;	//当前行号,当前行长度,保留字长度
	int	fdLen = 0;
	int	rwLen = 0;
	struct ResWord	rWord;	
	
	std::ifstream	Efile;
	std::ifstream	Cfile;

	Efile.open("MatchStr.cpp");
	Cfile.open("C++Word.txt");

	rWord.count = 0;		

	while(!Cfile.eof())
	{
		char ch;

		Cfile.get(ch);

		if (Cfile.eof())
		{
			break;
		}

		if ((ch >= 'a' && ch <= 'z') || (ch >= 'A' && ch <= 'Z') || '_' == ch)
		{
			rWord.str[rwLen++] = ch;		
		}
		else if (rwLen != 0)
		{
			rWord.str[rwLen] = '/0';  //找出一个保留字

			while(!Efile.eof())
			{
				Efile.get(ch);

				if (Efile.eof())
				{
					break;
				}

				if (ch != '/n')      
				{
					fdata[fdLen++] = ch;   //查找一行的字符
				}
				else
				{
					row++;

					if (fdLen != 0)  //逐行比较
					{
						fdata[fdLen] = '/0';	//提取一行数据
						//KMP算法的next地址
						int *k_next = new int[strlen(fdata)];	

						Kmp_next(fdata, k_next);

						//如果该行有匹配成功,则加入该行号
						if (Kmp(fdata, rWord, k_next))    
						{
							rWord.iList.push_back(row);
						}
					}
					else    
					{
						continue;	//跳过空行
					}

					fdLen = 0;
				}
			}

			//输出当前关键字的信息
			cout<< rWord.str<< ' '<< rWord.count<< ' ';

			std::list::iterator  iter;

			iter = rWord.iList.begin();

			while(iter != rWord.iList.end())
			{
				cout<< *iter<< '-';
				iter++;
			}
			cout<< endl;
			
			rWord.iList.clear();   
			rWord.count = 0;	//出现次数清0
			rwLen = 0;		//查找保留字的下标回滚到0
			row = 0;	
			//文件流指针指向文件头部

			Efile.clear();
			Efile.seekg(0);	
		}
		else 
		{
			continue;   //跳过两单词间的字符...
		}
	}

	Cfile.close();
	Efile.close();
}

  • 2
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值