L-9 MCS 275 Mon 29 Jan 2001

Below is the listing for the program we discussed in class.
/* L-9 MCS 275 frequency table for key words on a line */

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

#define  MAXLEN  80    /* maximum #characters in string */

int read_line (char s[]);
/* Reads a line of characters (until user hits enter).
   The string read is in "s" and the function returns the number
   "n" of characters in the string, i.e.: s[n] == '\0' (See L-5) */
int read_keywords (char *keys[]);
/* reads key words, stored in keys, returns number of key words */
int scan_next_word (char s[], int i, char word[]);
/* scans the string s for the next word, starting at position i,
   the integer on return is the next current position in s */
int match_word (int n, char *keys[], char word[]);
/* if keys[i] == word[i], then i, otherwise -1 is returned */
void freqkeys (char s[], int n, char *keys[], int freq[]);
/* on return freq[i] contains the #occurrences of keys[i] in s */

int main()
{
   char line[MAXLEN];
   char *keys[MAXLEN];
   int i,n,m;
   int freq[MAXLEN];

   printf("Give a line (< %d characters) : ", MAXLEN);
   n = read_line(line);
   printf("Your line is :\n     \"%s\" \n", line);
   printf("There are %d characters on this line\n", n);
   m = read_keywords(keys);
   freqkeys(line,m,keys,freq);
   printf("Frequency table of %d key words :\n", m);
   for (i=0; i < m; ++i)
      printf("   \"%s\"  : %d \n", keys[i], freq[i]);
   return 0;
}

int read_line (char s[])
{
   int c,i;
   for (i=0; (c=getchar()) != EOF && c != '\n' && i < MAXLEN; ++i)
      s[i] = c;
   s[i] = '\0';
   return i;
}

int read_keywords (char *keys[])
{
   int i;
   char word[MAXLEN];

   printf("Reading key words, type 0 to stop.\n");
   for (i=0; ; i++)
   {
      printf("   Give key word : ");
      scanf("%s", word);
      if (strcmp(word,"0") == 0)
         break;
      else
      {
         keys[i] = calloc(MAXLEN, sizeof(char));
         strcpy(keys[i],word);
      }
   }
  return i;
}

int scan_next_word (char s[], int i, char word[])
{
   int j=i;
   int ind=0;

   while (s[j] == ' ') j++;
   if (s[j] != '\0')
      while ((s[j] != ' ') && (s[j] != '\0'))
         word[ind++] = s[j++];
   word[ind] = '\0';
   return j;
}

int match_word (int n, char *keys[], char word[])
{
   int i;
   for (i=0; i < n; i++)
      if (strcmp(word,keys[i]) == 0)
         return i;
   return -1;
}

void freqkeys (char s[], int n, char *keys[], int freq[])
{
   int i=0;
   int j;
   char word[MAXLEN];

   while (s[i] != '\0')
   {
      i = scan_next_word(s,i,word);
      j = match_word(n,keys,word);
      if (j >= 0)
         freq[j]++;
   }
}