C bootcamp · Lab 48

Word frequency

mediumStrings15 minLesson: Strings

Read the question, write C on the right, then Run or Check.

QuestionHint and solution stay closed until you open them

Read one line of lowercase words. Print each distinct word and its count, alphabetically.

Format: word then space then count, one pair per line.

Input. One line of space-separated lowercase words.

Output. Lines of "word count" sorted by word.

Examples

Example 1
Input
the cat the dog the
Output
cat 1
dog 1
the 3
Hint
  1. Store unique words in a small array of structs; bubble-sort by word.
Show correct code

Peek only after you have tried. You can still Check your own version.

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

typedef struct { char w[64]; int c; } Pair;

int main(void) {
  char line[512];
  if (!fgets(line, sizeof line, stdin)) return 0;
  Pair p[64];
  int n = 0;
  for (char *tok = strtok(line, " \t\r\n"); tok; tok = strtok(NULL, " \t\r\n")) {
    int i;
    for (i = 0; i < n; i++) if (strcmp(p[i].w, tok) == 0) { p[i].c++; break; }
    if (i == n) { strncpy(p[n].w, tok, 63); p[n].w[63] = 0; p[n].c = 1; n++; }
  }
  for (int i = 0; i < n; i++)
    for (int j = i + 1; j < n; j++)
      if (strcmp(p[i].w, p[j].w) > 0) { Pair t = p[i]; p[i] = p[j]; p[j] = t; }
  for (int i = 0; i < n; i++) printf("%s %d\n", p[i].w, p[i].c);
  return 0;
}
main.cC17 · gcc · Ctrl + Enter runs
ResultIdle
Run to see output. Check grades the tests.