C 语言统计关键字出现次数

#include <stdio.h>
#include <ctype.h>
#include <string.h>

#define NKEYS (sizeof keytab / sizeof(struct key))

struct key 
{
char *word;
int count;
};

/*关键字列表(注意一定要按字典排序)*/
struct key keytab[15] = 
{
  "abort",0,
   "break",0,
   "clock",0,
   "define",0,
   "echo",0,
   "fgetc",0,
   "get",0,
   "help",0,
   "insert",0,
   "jump",0,
   "kind",0,
   "long",0,
   "malloc",0,
   "null",0,
   "operate",0

};

int binarysearch(char *word, struct key tab[], int n);
int getword(char *word);


/*<The C programming language (second edition) 中的小练习>

  功能:统计输入文本中关键字出现的次数。
*/
int main()
{
  char word[30];
  int n;

  while(getword(word) != 0 && strcmp(word,"quit") != 0)
  {
    if((n = binarysearch(word,keytab,NKEYS )) >= 0);
	   keytab[n].count++;
  }
  for(n = 0; n < NKEYS; n++)
  {
    if(keytab[n].count > 0)
		printf("%s  :  %d\n",keytab[n].word,keytab[n].count);
  }
 
  return 0;
}

/*从输入端得到一个单词*/
int getword(char *word)
{ char c;
  int i = 0;

  while(isspace(c = getchar()))
	  ;
  while(1)
  {
	  if(c != '\n' && c != ' ' && c != '\t' && isalpha(c))
	     word[i++] = c;
	  if(c == '\n' || c == ' ' )
	  {   
		  word[i] = '\0';
		  
		  return i;
	  }
	  c = getchar();
  } 
  return i;
}

/*binarysearch 函数: 在tab[0]到tab[n]中查找单词*/
int binarysearch(char *word, struct key tab[], int n)
{
  int mid,l,h,flag;
  l= 0;
  h = n - 1;

  while(l <= h)
  {
    mid = (l + h)/2;
	if( (flag = strcmp(word,tab[mid].word)) < 0)
		h = mid - 1;
	else if(flag > 0)
		l = mid + 1;
	else
		return mid;
  
  
  }
     
  return -1;
}

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值