HansJack

HansJack

Array Case p124: Letter Frequency Count

p124 Array Case: Letter Frequency Count#

#include <stdio.h>
#include <stdint.h>
#include <inttypes.h>
#include <limits.h>
#include <ctype.h>

#define LETTER_COUNT 26

int main(void)
{
    uint32_t frequency[LETTER_COUNT] = { 0 };

    char text[] = "Example text for frequency analysis.\0";

    // Count the occurrences of each letter
    for (uint32_t i = 0; text[i] != '\0'; i++)
    {
        char ch = tolower(text[i]);

        if (ch >= 'a' && ch <= 'z') {
            frequency[ch - 'a']++;
        }
    }

    puts("Character Frequency:\n");
    for (int i = 0; i < LETTER_COUNT; i++) {
        if (frequency[i] > 0) {
        printf("'%c': %d\n", 'a' + i, frequency[i]); 
        }
    }
    return 0;
}

After Enhancement:

#include <stdio.h>
#include <stdint.h>
#include <inttypes.h>
#include <limits.h>
#include <ctype.h>
#include <string.h>  // Include strcspn function

#define LETTER_COUNT 26
#define MAX_TEXT_LENGTH 256  // Define maximum input length

int main(void)
{
	uint32_t frequency[LETTER_COUNT] = { 0 };

	char text[MAX_TEXT_LENGTH];  // Used to store user input text

	//char text[] = "Example text for frequency analysis.\0";
	printf("Please enter text: ");
	fgets(text, sizeof(text), stdin);  // Use fgets to read a line of text

	// Handle newline character
	text[strcspn(text, "\n")] = '\0';  // Replace newline character with string terminator


	// Count the occurrences of each letter
	for (uint32_t i = 0; text[i] != '\0'; i++)
	{
		char ch = tolower(text[i]);

		if (ch >= 'a' && ch <= 'z') {
			frequency[ch - 'a']++;
		}
	}
	puts("Character Frequency:\n");
	for (int i = 0; i < LETTER_COUNT; i++) {
		if (frequency[i] > 0) {
			printf("'%c': %d\n", 'a' + i, frequency[i]);
		}
	}
	return 0;
}

image-20241025223719918 

This article is synchronized and updated by Mix Space to xLog. The original link is https://hansblog.top/posts/study-book/c-p124

Loading...
Ownership of this post data is guaranteed by blockchain and smart contracts to the creator alone.