C program to find the occurrence of each character in a string.
#include <stdio.h>
#include <string.h>
int main() {
char str[256];
int i = 0, index, characters[26] = {0};
/* get the input character from the user */
printf("Enter your input string:");
fgets(str, 256, stdin);
str[strlen(str) - 1] = '\0';
/* count the frequency of characters */
while (str[i] != '\0') {
if (str[i] >= 'A' && str[i] <= 'Z') {
/* index manipulation from input character */
index = str[i] - 'A';
/*
* increment the value at the
* above manipulated index
*/
characters[index]++;
} else if (str[i] >= 'a' && str[i] <= 'z') {
index = str[i] - 'a';
characters[index] = characters[index] + 1;
}
i++;
}
#include <string.h>
int main() {
char str[256];
int i = 0, index, characters[26] = {0};
/* get the input character from the user */
printf("Enter your input string:");
fgets(str, 256, stdin);
str[strlen(str) - 1] = '\0';
/* count the frequency of characters */
while (str[i] != '\0') {
if (str[i] >= 'A' && str[i] <= 'Z') {
/* index manipulation from input character */
index = str[i] - 'A';
/*
* increment the value at the
* above manipulated index
*/
characters[index]++;
} else if (str[i] >= 'a' && str[i] <= 'z') {
index = str[i] - 'a';
characters[index] = characters[index] + 1;
}
i++;
}
/* print the result */
printf("Characters Frequency\n");
for (i = 0; i < 26; i++) {
if (characters[i] > 0) {
printf("%-10c => %3d\n", ('a' + i), characters[i]);
}
}
return 0;
}
Output:
jp@jp-VirtualBox:~/$ ./a.out
Enter your input string:c programming language
Characters Frequency
a => 3
c => 1
e => 1
g => 4
i => 1
l => 1
m => 2
n => 2
o => 1
p => 1
r => 2
u => 1
Enter your input string:c programming language
Characters Frequency
a => 3
c => 1
e => 1
g => 4
i => 1
l => 1
m => 2
n => 2
o => 1
p => 1
r => 2
u => 1
No comments:
Post a Comment