  # Algorithm : Find the number of occurrence of each character presents in a string ?

194 views
Algorithm : Find the number of occurrence of each character presents in a string ? posted Jun 28, 2015

+1 vote

Below is my solution :

you only have a need of one array of int .

``````int count;
char  string[]="jhgdkwjhfoeirjbvndbjhegriuegbv";

for(int i=0;i<strlen(string); i++)
{
count[(int)string[i]]++;
}

for(int i=0;i<256;i++)
{
if(count[i])
cout<<(char)(i)<<" "<<count[i];
}
`````` answer Oct 31, 2015

This C Program counts the number of occurrence of each character ignoring the case and prints them.

``````/*
* C Program to Count the Number of Occurrence of
* each Character Ignoring the Case of Alphabets
* & Display them
*/
#include <stdio.h>
#include <string.h>
#include <ctype.h>

struct detail
{
char c;
int freq;
};

int main()
{
struct detail s;
char string, c;
int i = 0, index;

for (i = 0; i < 26; i++)
{
s[i].c = i + 'a';
s[i].freq = 0;
}
printf("Enter string: ");
i = 0;
do
{
fflush(stdin);
c = getchar();
string[i++] = c;
if (c == '\n')
{
break;
}
c = tolower(c);
index = c - 'a';
s[index].freq++;
} while (1);
string[i - 1] = '\0';
printf("The string entered is: %s\n", string);

printf("*************************\nCharacter\tFrequency\n*************************\n");
for (i = 0; i < 26; i++)
{
if (s[i].freq)
{
printf("     %c\t\t   %d\n", s[i].c, s[i].freq);
}
}

return 0;
}
``````

Enter string: A quIck brOwn fox JumpEd over a lazy dOg

The string entered is: A quIck brOwn fox JumpEd over a lazy dOg

### Character Frequency

`````` a         3
b         1
c         1
d         2
e         2
f         1
g         1
i         1
j         1
k         1
l         1
m          1
n         1
o         4
p         1
q         1
r         2
u         2
v         1
w           1
x         1
y         1
z         1
`````` answer Jul 14, 2015
Similar Questions

1,1,2,2,2,6,6,6,7,7,7,7,7,7,7,8,8,9,9,9

Example:
Input = 1 Output=0 (First index of 1).
Input = 2 Output=2 (First index of 2).
Input = 6 Output= 5 (First index of 6).
Input = 7 Output= 8 (First index of 7).
Input = 8 Output=15 (First index of 8).
Input = 9 Output=17 (First index of 9).