How it works...

Let's assume that the two string variables you have defined, str and chr, are of the size 80 (you can always increase the size of the strings if you wish).

We will assign the character string racecar to the str string. Each of the characters will be assigned to the respective index locations of str, that is, r will be assigned to index location str[0]a will be assigned to str[1], and so on. As always, the last element in the string will be a null character, as shown in the following diagram:

Figure 2.9

Using the strlen function,  we will first compute the length of the string. Then, we will use the string array chr for storing characters of the str array individually at each index location. We will execute a for loop beginning from 1 until the end of the string to access each character of the string.

The integer array we defined earlier, that is, count, will represent the number of times the characters from str have occurred, which is represented by the index locations in the chr array. That is, if r is at index location chr[0], then count[0] will contain an integer value (1, in this case) to represent the number of times the r character has occurred in the str string so far:

Figure 2.10

One of the following actions will be applied to every character that's accessed from the string:

When the for loop completes, that is when all of the characters in the string are accessed. The chr array will have individual characters of the string and the count array will have the count, or the number of times the characters represented by the chr array have occurred in the string. All of the elements in the chr and count arrays are displayed on the screen.

Let's use GCC to compile the countofeach.c program, as follows:

D:\CBook>gcc countofeach.c -o countofeach

Let's run the generated executable file, countofeach.exe, to see the output of the program:

D:\CBook>./countofeach
Enter a string: bintu
The count of each character in the string bintu is
b 1
i 1
n 1
t 1
u 1

Let's try another character string to test the results:

D:\CBook>./countofeach
Enter a string: racecar
The count of each character in the string racecar is
r 2
a 2
c 2
e 1

Voilà! We've successfully displayed the count of each character in a string.

Now, let's move on to the next recipe!