一个用于统计输入中各个C语言关键字出现次数的程序

       考虑写一个用于统计输入中各个C语言关键字出现次数的程序。我们可以用一个字符串数组来存放关键字名,一个整型数组存放相应关键字的出现次数。

        另外一种方法是我们直接用结构体来表示。本例采用用结构体的方法。

完整代码如下:

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

#define MAXWORD 100
#define NKEYS (sizeof(keytab) / sizeof(keytab[0]))

int getword(char *, int);
//int binsearch(char *, struct key *, int);

struct key
{
  char *word;
  int count;
} keytab[] = {
   "auto", 0,
   "break", 0,
   "case", 0,
   "char", 0,
   "const", 0,
   "continue", 0,
   "default", 0,
   "do", 0,
   "double", 0,
   "else", 0,
   "enum", 0,
   "extern", 0,
   "float", 0,
   "for", 0,
   "goto", 0,
   "if", 0,
   "int", 0,
   "long", 0,
   "register", 0,
   "return", 0,
   "short", 0,
   "signed", 0,
   "sizeof", 0,
   "static", 0,
   "struct", 0,
   "switch", 0,
   "typedef", 0,
   "union", 0,
   "unsigned", 0,
   "void", 0,
   "volatile", 0,
   "while", 0
};

int main(void)
{
   int n;
   char word[MAXWORD];

   while(getword(word, MAXWORD) != EOF)
        if(isalpha(word[0]))
		   if((n = binsearch(word, keytab, NKEYS)) >= 0)
		       keytab[n].count++;
   for(n=0; n<NKEYS; n++)
       if(keytab[n].count > 0)
	      printf("%4d %s\n",
		      keytab[n].count, keytab[n].word);
   return 0;
}

int binsearch(char *word, struct key *keytab, int n)
{
   int cond;
   int low = 0;
   int high = n - 1;
   int mid;
   while(high >= low)
   {
      mid = low + (high - low) / 2;
      if((cond = strcmp(word, keytab[mid].word)) < 0)
	     high = mid - 1;
      else if(cond > 0)
	     low = mid + 1;
      else
	     return mid;
   }
   return -1;
}

int getword(char *word, int lim)
{
    int c, getch(void);
	void ungetch(int);
	char *w = word;

	while(isspace(c = getch()))
	     ;
    if(c != EOF)
	   *w++ = c;
	if(!isalpha(c))
	{
	   *w = '\0';
	   return c;
	}
	for(; --lim > 0; w++)
	   if(!isalnum(*w = getch()))
	   {
	      ungetch(*w);
		  break;
	   }
	*w = '\0';
    return word[0];
}

#define BUFSIZE 100
char buf[BUFSIZE];

int bufp = 0;
int getch(void)
{
   return (bufp > 0) ? buf[--bufp] : getchar();
}

void ungetch(int c)
{
     if(bufp > BUFSIZE)
	   printf("ungetch: too many characters");
	 else
	   buf[bufp++] = c;
}

程序运行结果:


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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值