String Alphabet Count
Count the frequency of each alphabet character in a given string and display them in alphabetical order.
Understand the Problem
Problem Statement
String Alphabet Count: Given a string S with only alphabets, print the alphabet and its count as shown in the Example Input/Output section.
Constraints
- 1 <= Length of S <= 100
- String S contains only alphabetic characters (a-z, A-Z)
- Case sensitivity: treat uppercase and lowercase as distinct characters
- Output must be sorted alphabetically by character
Examples
applea1 e1 l1 p2In 'apple': 'a' appears 1 time, 'e' appears 1 time, 'l' appears 1 time, 'p' appears 2 times. Output is sorted alphabetically.
helloe1 h1 l2 o1In 'hello': 'e' appears 1 time, 'h' appears 1 time, 'l' appears 2 times, 'o' appears 1 time. Output is sorted alphabetically.
aabbcca2 b2 c2In 'aabbcc': each character 'a', 'b', and 'c' appears exactly 2 times. Output is sorted alphabetically.
Solution
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
int compare(const void *a, const void *b) {
return (*(char*)a - *(char*)b);
}
int main() {
char s[101];
fgets(s, sizeof(s), stdin);
// Remove newline if present
int len = strlen(s);
if (s[len-1] == '\n') {
s[len-1] = '\0';
len--;
}
// Create sorted copy for ordering
char sorted[101];
strcpy(sorted, s);
qsort(sorted, len, sizeof(char), compare);
// Create unique character array
char unique[101];
int unique_count = 0;
for (int i = 0; i < len; i++) {
int found = 0;
for (int j = 0; j < unique_count; j++) {
if (unique[j] == sorted[i]) {
found = 1;
break;
}
}
if (!found) {
unique[unique_count++] = sorted[i];
}
}
// Print results
for (int i = 0; i < unique_count; i++) {
int count = 0;
for (int j = 0; j < len; j++) {
if (s[j] == unique[i]) {
count++;
}
}
printf("%c%d", unique[i], count);
if (i < unique_count - 1) {
printf(" ");
}
}
return 0;
}C Solution Explanation:
1. Read input string using fgets() and remove trailing newline
2. Create a sorted copy of the string using qsort() to determine output order
3. Extract unique characters from sorted string using nested loops
4. For each unique character, count occurrences in original string
5. Print character and count, with spaces between pairs
6. Uses standard C library functions for sorting and string manipulation