top of page

1  #include<stdio.h>
2  #include<string.h>
3  #include<ctype.h>
 
4  struct word {
5     char *word;
6     int   count;
7  };
 
8  struct word keywords[] ={
9     {"double", 0},
10    {"else",   0},
11    {"for",    0},
12    {"if",     0},
13    {"int",    0},
14    {"while",  0}
15 };
 
16 #define NWORDS (sizeof keywords/sizeof(struct word))
 
17 int getword(char *);
18 int binsearch(char *);
 
19 int main(void){
20    char next_word[80];
21    int n;
 
22    while(getword(next_word))
23       if((n=binsearch(next_word))>=0)
24          keywords[n].count++; /* (keywords+n)->count++  */
 
25    for(n=0; n<NWORDS; n++)
26       printf("%s\t%d\n",keywords[n].word, (keywords+n)->count);
 
27    return 0;
28 }
 
29 int getword(char *word){
 
30    int c;
31    while(!isalpha(c=getchar()))
32       if(c==EOF){
33          return 0;
34       }
 
35    *word=c;
36    while(isalpha(*++word=getchar()));
37    *word='\0';
38    return 1;
39 }
 
40 int binsearch(char *word){
41    int low=0;
42    int high=NWORDS-1;
43    int mid;
44    int res;
 
45    while(low <= high){
46       mid=(low+high)/2;
47       res=strcmp(word,(keywords+mid)->word);
48       if(res<0){
49          high=mid-1;
50       }
51       else if(res>0) {
52          low=mid+1;
53       }
54       else return mid;
55    }
56    return -1;
57 }
 

  • b-facebook
  • Twitter Round
  • b-googleplus
bottom of page