问题

编写 一个程序,统计输入中C语言每个关键字的出现次数。

算法分析

While ( 仍有新单词读入)
    If(新单词是否是关键字)
        相应关键字出现次数加1;
输出关键字及出现次数;

定义一个结构用以表示关键字与其出现次数:

struct   Key {
char *keyword;
int count;
};

关键字表的组织:使用一个有序(提高效率)的结构数组来存放关键字表及关键字出现次数:

struct   Key   Keytab[ ] = {
"auto", 0,
"break",0,
"case", 0,
...
"while", 0
};

在有序数据集中查找指定数据项最常用及最快的算法是折半查找算法

算法实现

#include <stdio.h>
struct Key {
char *keyword;
int keycount;
} Keytab[ ] = {
"auto", 0,
"break", 0,
"case", 0,
...
"while", 0
};
#define
#define
#define
#define

struct Key *binary(char *word, struct Key tab[ ], int n);
char getword(char *w, int lim);
char type( int c);
void printKey(struct Key tab[ ], int n);

int main( ) /* count C keyword */
{
int t;
char word[MAXWORD];
struct Key *p;

while((t = getword(word, MAXWORD)) != EOF)
if( t = = LETTER)
if(( p = binary(word, Keytab, NKEYS)) != NULL)
p->keycount++;
printKey(keytab, NKEYS);
return 0;
}

struct Key *binary(char *word, struct Key tab[ ], int n)
{
int cond;
struct Key *low = &tab[0];
struct Key *high = &tab[n-1];
struct Key *mid;

while(low <= high){
mid = low + (high low) / 2;
if((cond = strcmp(word, mid->keyword)) < 0)
high = mid 1;
else if ( cond > 0)
low = mid + 1;
else
return (mid);
}
return (NULL);
}

char getword(char *w, int lim)
{
int c, t;

if(type(c = *w++ = getchar( )) != LETTER){
*w = '\0';
return ( c);
}
while(--lim > 0) {
t = type(c = *w++ = getchar( ));
if( t != LETTER && t != DIGIT){
ungetc(c,stdin);
break;
}
}
*(w-1) = '\0';
return ( LETTER);
}

char type(int c) /* return type of ASCII character */
{
if( c >= 'a' && c <= 'z' || c >= 'A' && c <= 'Z')
return ( LETTER );
else if ( c >= '0' && c <= '9')
return ( DIGIT );
else return (c);
}

void printKey(struct Key tab[ ], int n)
{
struct Key *p;
for(p=Keytab, p < Keytab+n; p++)
if(p->keycount > 0)
printf("%4d%s\n", p->keycount, p->keyword);
}