Skip to main content

Lesson 6 of 7

Mini Project Part 4 - Word Frequency Counter

Build a word frequency counter that reads a text string, tokenises it using `strtok`, converts each word to lowercase, and counts how many times each unique word appears. Applies: char arrays, string functions (strtok, strlen, strcasecmp/tolower, strcmp), 2D char arrays for the word table, and careful buffer handling.

16 minBy Priygop Editorial TeamUpdated 2026Peer Reviewed & Verified

Word Frequency Counter - Complete Implementation

Word Frequency Counter - Complete Implementation
/* wordfreq.c - count word frequencies in a text string */
#include <stdio.h>
#include <string.h>
#include <ctype.h>

#define MAX_WORDS  128
#define MAX_WORD_LEN 64

/* Convert string to lowercase in-place */
static void to_lower(char *s) {
    for (; *s; s++) *s = (char)tolower((unsigned char)*s);
}

/* Strip leading/trailing punctuation from a word */
static void strip_punct(char *word) {
    /* Remove trailing punctuation */
    int len = (int)strlen(word);
    while (len > 0 && !isalnum((unsigned char)word[len-1])) {
        word[--len] = '';
    }
}

int main(void) {
    const char *text =
        "To be or not to be that is the question "
        "whether tis nobler in the mind to suffer "
        "the slings and arrows of outrageous fortune "
        "or to take arms against a sea of troubles";

    /* Word table - 2D char array */
    char  words[MAX_WORDS][MAX_WORD_LEN];
    int   freq[MAX_WORDS];
    int   unique = 0;

    /* Make a writable copy - strtok modifies it */
    char buf[1024];
    strncpy(buf, text, sizeof(buf) - 1);
    buf[sizeof(buf) - 1] = '';

    /* Tokenise by spaces */
    char *token = strtok(buf, " 	
,.!?;:");
    while (token != NULL && unique < MAX_WORDS) {
        strip_punct(token);
        to_lower(token);

        if (strlen(token) == 0) {
            token = strtok(NULL, " 	
,.!?;:");
            continue;
        }

        /* Search existing words */
        int found = 0;
        for (int i = 0; i < unique; i++) {
            if (strcmp(words[i], token) == 0) {
                freq[i]++;
                found = 1;
                break;
            }
        }

        /* New word */
        if (!found) {
            strncpy(words[unique], token, MAX_WORD_LEN - 1);
            words[unique][MAX_WORD_LEN - 1] = '';
            freq[unique] = 1;
            unique++;
        }

        token = strtok(NULL, " 	
,.!?;:");
    }

    /* Sort by frequency (bubble sort for simplicity) */
    for (int i = 0; i < unique - 1; i++) {
        for (int j = 0; j < unique - i - 1; j++) {
            if (freq[j] < freq[j+1]) {
                /* Swap freq */
                int tmp = freq[j]; freq[j] = freq[j+1]; freq[j+1] = tmp;
                /* Swap words */
                char wtmp[MAX_WORD_LEN];
                strncpy(wtmp, words[j], MAX_WORD_LEN);
                strncpy(words[j], words[j+1], MAX_WORD_LEN);
                strncpy(words[j+1], wtmp, MAX_WORD_LEN);
            }
        }
    }

    /* Print results */
    printf("%-20s  %s
", "Word", "Count");
    printf("%-20s  %s
", "----", "-----");
    for (int i = 0; i < unique; i++) {
        printf("%-20s  %d
", words[i], freq[i]);
    }

    return 0;
}
/* Build: gcc -Wall -Wextra -std=c99 wordfreq.c -o wordfreq
   Run:   ./wordfreq                                         */

Common Mistakes

  • Passing `text` directly to `strtok` - `strtok` modifies the input. A string literal is read-only. Always copy to a writable buffer first.
  • 2D array dimension confusion - `words[MAX_WORDS][MAX_WORD_LEN]` stores MAX_WORDS strings each of at most MAX_WORD_LEN chars. The first dimension is the number of strings; the second is the max length of each.
  • Not null-terminating after `strncpy` of the word into the table - when `token` is exactly `MAX_WORD_LEN-1` chars, `strncpy` fills all bytes but does not null-terminate. Always add `words[unique][MAX_WORD_LEN-1] = '';`.

Tip

Tip

Practice Mini Project Part 4 Word Frequency Counter in small, isolated examples before integrating into larger projects. Breaking concepts into small experiments builds genuine understanding faster than reading alone.

Diagram
Loading diagram…

Text processing pipeline tokenizes words, tracks frequencies, and sorts results

Practice Task

Note

Practice Task - (1) Write a working example of Mini Project Part 4 Word Frequency Counter from scratch without looking at notes. (2) Modify it to handle an edge case (empty input, null value, or error state). (3) Share your solution in the Priygop community for feedback.

Quick Quiz

Common Mistake

Warning

A common mistake with Mini Project Part 4 Word Frequency Counter is skipping edge case testing - empty inputs, null values, and unexpected data types. Always validate boundary conditions to write robust, production-ready c code.

Key Takeaways

  • Build a word frequency counter that reads a text string, tokenises it using `strtok`, converts each word to lowercase, and counts how many times each unique word appears.
  • Passing `text` directly to `strtok` - `strtok` modifies the input. A string literal is read-only. Always copy to a writable buffer first.
  • 2D array dimension confusion - `words[MAX_WORDS][MAX_WORD_LEN]` stores MAX_WORDS strings each of at most MAX_WORD_LEN chars. The first dimension is the number of strings; the second is the max length of each.
  • Not null-terminating after `strncpy` of the word into the table - when `token` is exactly `MAX_WORD_LEN-1` chars, `strncpy` fills all bytes but does not null-terminate. Always add `words[unique][MAX_WORD_LEN-1] = '';`.

Topics in This Module

0/7 done