C Program to Count the Occurrences of Each Character in a String

C Program to Count the Occurrences of Each Character in a String

Counting the occurrences of each character in a string is a common programming task. It helps you analyze text, understand frequency patterns, and build applications such as word counters, text analyzers, and encryption programs.

In C, strings are arrays of characters ending with a null terminator (\0). By scanning the string character by character, we can tally the number of times each character appears. This tutorial will guide you through writing a C program that counts the occurrences of every character in a string. We will also explain multiple approaches, including using arrays and pointers.

Understanding the Problem

Given a string, the goal is to find out how many times each character occurs. For simplicity, we can assume ASCII characters, so we have 256 possible characters.

The main idea is:

  1. Initialize a count array of size 256 to zero.
  2. Traverse the string character by character.
  3. For each character, increment the corresponding count in the array.
  4. Finally, print only the characters that appear at least once.

This problem emphasizes arrays, character manipulation, and understanding ASCII values in C.

Program 1: Using a Count Array

We will start by using an integer array to store the counts of each character.

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

int main() {

    char str[100];
    int count[256] = {0};  // Initialize count array to zero

    printf("Enter a string: ");
    fgets(str, sizeof(str), stdin);

    // remove newline character if present
    str[strcspn(str, "\n")] = '\0';

    // Count occurrences
    for (int i = 0; str[i] != '\0'; i++) {
        count[(unsigned char)str[i]]++;
    }

    // Print results
    printf("Character occurrences:\n");

    for (int i = 0; i < 256; i++) {

        if (count[i] > 0) {
            printf("'%c' : %d\n", i, count[i]);
        }

    }

    return 0;

}

This program uses a simple array of 256 integers to count each character. By casting the character to unsigned char, we ensure correct indexing in the count array.

Program 2: Using Pointers

We can also use pointers to traverse the string and update the count array.

#include <stdio.h>

int main() {

    char str[100], *ptr;
    int count[256] = {0};

    printf("Enter a string: ");
    fgets(str, sizeof(str), stdin);

    for (ptr = str; *ptr != '\0'; ptr++) {

        if (*ptr == '\n') {
            *ptr = '\0';
            break;
        }

        count[(unsigned char)*ptr]++;

    }

    printf("Character occurrences:\n");

    for (int i = 0; i < 256; i++) {

        if (count[i] > 0) {
            printf("'%c' : %d\n", i, count[i]);
        }

    }

    return 0;

}

Using a pointer allows you to traverse the string without indexing, demonstrating how strings are memory sequences. The logic is the same as the previous method.

Program 3: Ignoring Case

Sometimes, we want ‘A’ and ‘a’ to be counted as the same character. We can achieve this by converting each character to lowercase using a conditional check.

#include <stdio.h>
#include <ctype.h>

int main() {

    char str[100];
    int count[256] = {0};

    printf("Enter a string: ");
    fgets(str, sizeof(str), stdin);

    for (int i = 0; str[i] != '\0'; i++) {

        if (str[i] == '\n') str[i] = '\0';
        else count[(unsigned char)tolower(str[i])]++;

    }

    printf("Character occurrences (case-insensitive):\n");

    for (int i = 0; i < 256; i++) {

        if (count[i] > 0) {
            printf("'%c' : %d\n", i, count[i]);
        }

    }

    return 0;

}

This version uses the tolower() function to normalize characters, so ‘A’ and ‘a’ are counted together.

FAQs

1. Can this program handle spaces and punctuation?
Yes, every character, including spaces, digits, and punctuation, is counted.

2. How do I make the program case-sensitive or case-insensitive?
By default, it is case-sensitive. To make it case-insensitive, use tolower() or toupper() before incrementing the count.

3. Can this work with Unicode characters?
This program works for ASCII characters only. Handling Unicode requires a more advanced approach with larger arrays or special libraries.

Conclusion

Counting character occurrences in a string is a fundamental operation that teaches arrays, pointers, and character manipulation in C.

We explored three methods: using a count array with loops, using pointers, and case-insensitive counting. By practicing these methods, you will be able to analyze text efficiently and build a strong foundation for more complex string processing tasks.

References & Additional Resources

A collection of trusted tutorials, textbooks, and documentation for understanding strings, pointers, and character handling in C.

  1. Kernighan, Brian W., and Dennis M. Ritchie. The C Programming Language, 2nd Edition, Prentice Hall, 1988 – The definitive guide to C, covering arrays, strings, and pointer concepts.
  2. GeeksforGeeks: Count Frequency of Characters in C – Step-by-step explanation to calculate character frequencies in strings.
  3. Tutorialspoint: C Strings – Introduction to string declaration, initialization, and common operations in C.
  4. Cprogramming.com: Pointers in C – Beginner-friendly guide explaining pointers and their role in string manipulation.
  5. cplusplus.com: ctype.h Functions – Reference for character-handling functions like isalpha(), islower(), and toupper().
Scroll to Top