C Program to Count Frequency of Each Character in String

1. Introduction

Strings are sequences of characters. At times, it's necessary to analyze these sequences for particular patterns or data points, such as the frequency of each character in a string. This task has applications in cryptography, data analysis, and text processing. In this post, we will explore a C program that counts the frequency of each character in a given string.

2. Program Overview

1. Read a string input from the user.

2. Initialize an array of size 256 (to account for all ASCII characters) to zero.

3. Iterate through each character of the string and use its ASCII value as an index to increment the corresponding position in the array.

4. Finally, display the frequencies of characters that appear in the string.

3. Code Program

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

int main() {
    char str[100];
    int frequency[256] = {0};  // Array to hold frequencies of ASCII characters
    int i;

    // Read string input from the user
    printf("Enter a string: ");
    gets(str);

    // Calculate frequency of each character
    for(i = 0; str[i] != '\0'; i++) {
        frequency[(int)str[i]]++;
    }

    // Display the frequencies
    printf("Character frequencies:\n");
    for(i = 0; i < 256; i++) {
        if(frequency[i] != 0) {
            printf("'%c' = %d\n", i, frequency[i]);
        }
    }

    return 0;
}

Output:

For the string: "hello"
Character frequencies:
'h' = 1
'e' = 1
'l' = 2
'o' = 1

4. Step By Step Explanation

1. The program starts by declaring a string str and an array frequency of size 256 initialized to zero.

2. The user is then prompted to enter a string.

3. We then iterate through each character of the string using a for loop.

4. For each character, we use its ASCII value (obtained by type-casting the character to int) as an index to the frequency array and increment the value at that index.

5. Once all characters have been processed, we loop through the frequency array to display the frequencies of characters that have a non-zero count.

Note: The function gets() is traditionally used in C for reading strings, but it's worth noting that this function is unsafe because it can lead to buffer overflows. For more robust applications, consider using alternatives like fgets().

Comments