69,335
社区成员
发帖
与我相关
我的任务
分享
#include<stdio.h>
#include<ctype.h>
#include<string.h>
struct key{
char *word;
int count;
};
struct key keytab[] = { //关键字列表必须按升序存储在keytab中
"auto", 0,
"break", 0,
"case", 0,
"char", 0,
"const", 0
};
#define NKEYS (sizeof keytab / sizeof(struct key))
#define MAXWORD 100
int getword(char *, int);
int binsearch(char *, struct key *, int);
//统计输入中C语言关键字的个数
main()
{
int n;
char word[MAXWORD];
while(getword(word, MAXWORD) != EOF)
if(isalpha(word[0])) //isalpha判断字符是否为英文字母,yes,return 非0;No,return 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;
}
#include<stdio.h>
#include<ctype.h>
#include<string.h>
//binsearch:在tab[0]...tab[n-1]中查找单词 折半查找函数
int binsearch(char *word, struct key tab[ ], int n)
{
int cond;
int low, high, mid;
low = 0;
high = n - 1;
while(low <= high) {
mid = (low+high) / 2;
if((cond = strcmp(word, tab[mid].word)) < 0) //strcmp(s1,s2):判断两个字符串大小,s1 < s2 -;
high = mid - 1; //s1 > s2 +;
else if(cond > 0) //s1 = s2 0
low = mid + 1;
else
return mid;
}
return -1;
}
#include<stdio.h>
#include<ctype.h>
#include<string.h>
struct key{
char *word;
int count;
};
struct key keytab[] = {
{"auto", 0},
{"break", 0},
{"case", 0},
{"char", 0},
{"const", 0}
};
#define NKEYS (sizeof keytab / sizeof(struct key))
#define MAXWORD 100
int getword(char *, int);
int binsearch(char *, struct key *, int);
int main()
{
int i;
char word[MAXWORD];
//while(getword(word, MAXWORD) != EOF)
while(fgets(word, MAXWORD, stdin) != NULL) {
word[strlen(word) - 1] = 0;
if(isalpha(word[0]))
if((i = binsearch(word, keytab, NKEYS)) >= 0)
keytab[i].count++;
}
for(i = 0; i < NKEYS; i++)
if(keytab[i].count > 0)
printf("%4d %s\n", keytab[i].count, keytab[i].word);
return 0;
}
int binsearch(char *word, struct key tab[ ], int n)
{
int cond;
int low, high, mid;
low = 0;
high = n - 1;
while(low <= high) {
mid = (low+high) / 2;
if((cond = strcmp(word, tab[mid].word)) < 0)
high = mid - 1;
else if(cond > 0)
low = mid + 1;
else
return mid;
}
return -1;
}
这个方法是都写到一个源文件里,如果是多个源文件同时存在,建议添加一个头文件,将结构体的声明放在头文件里,然后多个源文件include该头文件#include<stdio.h>
#include<ctype.h>
#include<string.h>
#define NKEYS (sizeof keytab / sizeof(struct key))
#define MAXWORD 100
struct key{
char word[10];
int count;
};
key keytab[] = { //关键字列表必须按升序存储在keytab中
{"auto", 0},
{"break", 0},
{"case", 0},
{"char", 0},
{"const", 0}
};
int getword(char *, int);
int binsearch(char *, struct key *, int);
//统计输入中C语言关键字的个数
int main()
{
int n;
char word[MAXWORD];
while(getword(word, MAXWORD) != EOF)
if(isalpha(word[0])) //isalpha判断字符是否为英文字母,yes,return 非0;No,return 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;
}