How to do it…

  1. Create a string called str. The last element in the string will be a null character, \0
  2. Define another string called chr of matching length, to store the characters of str:
char str[80],chr[80];

  1. Prompt the user to enter a string. The entered string will be assigned to the str string:
printf("Enter a string: ");
scanf("%s",str);
  1. Compute the length of the string array, str, using strlen:
n=strlen(str);
  1. Define an integer array called count to display the number of times the characters have occurred in str:
int count[80];
  1. Execute chr[0]=str[0] to assign the first character of str to chr at index location chr[0].
  2. The count of the character that's assigned in the chr[0] location is represented by assigning 1 at the count[0] index location:
chr[0]=str[0];
count[0]=1;
  1. Run a for loop to access each character in str:
for(i=1;i < n;  i++)
  1. Run the ifexists function to find out whether the character of str exists in the chr string or not. If the character does not exist in the chr string, it is added to the chr string at the next index location and the respective index location in the count array is set to 1:
if(!ifexists(str[i], chr, x, count))
{
x++;
chr[x]=str[i];
count[x]=1;
}
  1. If the character exists in the chr string, the value in the respective index location in the count array is incremented by 1 in the ifexists function. The p and q arrays in the following snippet represent the chr and count arrays, respectively, since the chr and count arrays are passed and assigned to the p and q parameters in the ifexists function:
if (p[i]==u)
{
q[i]++;
return (1);
}

The countofeach.c program for counting each character in a string is as follows::

#include<stdio.h>
#include<string.h>
int ifexists(char u, char p[], int v, int q[])
{
int i;
for (i=0; i<=v;i++)
{
if (p[i]==u)
{
q[i]++;
return (1);
}
}
if(i>v) return (0);
}
void main()
{
char str[80],chr[80];
int n,i,x,count[80];
printf("Enter a string: ");
scanf("%s",str);
n=strlen(str);
chr[0]=str[0];
count[0]=1;
x=0;
for(i=1;i < n; i++)
{
if(!ifexists(str[i], chr, x, count))
{
x++;
chr[x]=str[i];
count[x]=1;
}
}
printf("The count of each character in the string %s is \n", str);
for (i=0;i<=x;i++)
printf("%c\t%d\n",chr[i],count[i]);
}

Now, let's go behind the scenes to understand the code better.