This project builds a word frequency counter: it reads a piece of text, splits it into words, counts how often each word appears, and prints the most common ones with a small bar chart. The same idea powers search engines, spam filters and tools that study writing style. Along the way it combines a hash table, string handling, dynamic memory and qsort with a custom comparison function.
In this project you will
- Split text into lower-case words with
<ctype.h> - Count words in a chained hash table
- Copy the entries into an array of pointers
- Sort by count, then alphabetically, with
qsort - Free every allocation and handle out-of-memory errors
This project uses hash tables, qsort, string handling and dynamic memory.
The Complete Program
/* Word frequency counter: hash table + dynamic array + qsort */
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <ctype.h>
#define BUCKETS 64
#define MAX_WORD 32
typedef struct Word {
char text[MAX_WORD];
int count;
struct Word *next;
} Word;
typedef struct {
Word *bucket[BUCKETS];
int unique, total;
} Counter;
static unsigned hash(const char *s) {
unsigned h = 5381;
while (*s) h = h * 33 + (unsigned char)*s++;
return h % BUCKETS;
}
static int add_word(Counter *c, const char *w) {
unsigned b = hash(w);
for (Word *p = c->bucket[b]; p; p = p->next)
if (strcmp(p->text, w) == 0) { p->count++; c->total++; return 1; }
Word *n = malloc(sizeof *n);
if (!n) return 0;
snprintf(n->text, sizeof n->text, "%s", w);
n->count = 1;
n->next = c->bucket[b];
c->bucket[b] = n;
c->unique++;
c->total++;
return 1;
}
/* Split text into lower-case words made of letters and apostrophes */
static int count_text(Counter *c, const char *text) {
char w[MAX_WORD];
int len = 0;
for (const char *p = text; ; p++) {
if (isalpha((unsigned char)*p) || (*p == '\'' && len > 0)) {
if (len < MAX_WORD - 1) w[len++] = (char)tolower((unsigned char)*p);
} else {
if (len > 0) {
w[len] = '\0';
if (!add_word(c, w)) return 0;
len = 0;
}
if (*p == '\0') break;
}
}
return 1;
}
static int by_count_then_text(const void *a, const void *b) {
const Word *x = *(Word * const *)a, *y = *(Word * const *)b;
if (x->count != y->count) return y->count - x->count; /* most frequent first */
return strcmp(x->text, y->text); /* then A to Z */
}
static void free_counter(Counter *c) {
for (int b = 0; b < BUCKETS; b++) {
Word *p = c->bucket[b];
while (p) { Word *next = p->next; free(p); p = next; }
}
}
int main(void) {
const char *text =
"The river gives the village water, and the village gives the river a name. "
"In the rainy season the river grows wide; in winter the river sleeps. "
"Children swim in the river, farmers water their fields, "
"and boats carry rice and fish from village to village.";
Counter c = {0};
if (!count_text(&c, text)) { free_counter(&c); return 1; }
/* Copy pointers into an array so they can be sorted */
Word **list = malloc(c.unique * sizeof *list);
if (!list) { free_counter(&c); return 1; }
int n = 0;
for (int b = 0; b < BUCKETS; b++)
for (Word *p = c.bucket[b]; p; p = p->next)
list[n++] = p;
qsort(list, n, sizeof *list, by_count_then_text);
printf("%d words, %d different\n\n", c.total, c.unique);
printf("Top 8 words\n");
for (int i = 0; i < 8 && i < n; i++) {
printf(" %-8s %2d ", list[i]->text, list[i]->count);
for (int k = 0; k < list[i]->count; k++) putchar('*');
putchar('\n');
}
int once = 0;
for (int i = 0; i < n; i++) if (list[i]->count == 1) once++;
printf("\nwords used only once: %d\n", once);
free(list);
free_counter(&c);
return 0;
}
Output
46 words, 26 different
Top 8 words
the 8 ********
river 5 *****
village 4 ****
and 3 ***
in 3 ***
gives 2 **
water 2 **
a 1 *
words used only once: 19
How It Works
1. Splitting the text into words
count_text reads one character at a time. Letters, and apostrophes inside a word, are added to the buffer w in lower case, so “The” and “the” count as the same word. Any other character, such as a space, comma or full stop, ends the current word. The loop also checks for '\0' after finishing a word, so the last word in the text is not lost. Words longer than 31 letters are cut short instead of overflowing the buffer.
2. Counting with a hash table
add_word hashes the word with djb2 to choose one of 64 buckets, then walks that bucket’s list. If the word is already there, its count goes up; otherwise a new Word node is added to the front. Each word’s text is stored inside its node, so one malloc per word is enough.
3. Sorting the results
A hash table has no useful order, so main copies a pointer to every entry into the array list, which has exactly c.unique slots. Sorting pointers is cheaper than sorting whole structs. The comparison function receives pointers to array elements, which are themselves pointers, hence *(Word * const *)a. It puts higher counts first, and breaks ties alphabetically with strcmp, so the output is the same on every run.
4. The report
The text has 46 words but only 26 different ones. “the” is used 8 times, “river” 5 times and “village” 4 times, and each line gets one star per use. 19 words appear only once.
5. Memory and errors
If any allocation fails, the program frees what it has and exits with status 1 instead of crashing. At the end it frees the pointer array and every node. The program was also tested under AddressSanitizer, which reported no leaks or invalid accesses.
Taking It Further
- Read the text from a file named on the command line with
fopenandfgetc. - Skip common “stop words” such as “the”, “and” and “a” by loading them into a second hash table.
- Let the user choose how many top words to show with a command-line argument.
- Grow the bucket array when the table becomes crowded, as in the open-addressing example.
Common Mistakes in Projects Like This
- Losing the last word because the loop stops at
'\0'before saving the word it was building. - Writing a comparison function as
a - bon large values, which can overflow. Counts here are small, but compare with(a > b) - (a < b)in general. - Casting the
qsortarguments wrongly, for example toWord *instead ofWord **. - Treating “River” and “river” as different words. Normalise case first.
Practice Exercises
Exercise 1. Print the longest word in the text and its length.
Show answer
const Word *longest = list[0];
for (int i = 1; i < n; i++)
if (strlen(list[i]->text) > strlen(longest->text))
longest = list[i];
printf("longest: %s (%zu letters)\n", longest->text, strlen(longest->text));
Exercise 2. Change the sort so that words with the same count are ordered by length, longest first.
Show answer
static int by_count_then_length(const void *a, const void *b) {
const Word *x = *(Word * const *)a, *y = *(Word * const *)b;
if (x->count != y->count) return y->count - x->count;
size_t lx = strlen(x->text), ly = strlen(y->text);
if (lx != ly) return lx < ly ? 1 : -1;
return strcmp(x->text, y->text);
}
Frequently Asked Questions
Can this program count Bangla words?
Not as written. isalpha and tolower work on single bytes, while Bangla text in UTF-8 uses several bytes per character. Handling it needs a Unicode-aware approach, such as wide characters with <wctype.h> or a library like ICU.
Why not just use a sorted array instead of a hash table?
Every new word would need a binary search plus shifting items to keep the array sorted. With thousands of different words, the hash table counts much faster, and the single sort at the end is cheap.
Summary
- Split text by checking each character, and normalise case.
- Count with a hash table; sort an array of pointers to the entries.
- A comparison function with a tie-breaker makes the output stable.
- Check every allocation and free everything at the end.
