Your problem is a classic frequency problem. Whenever you need to calculate the frequency of a set of values, you use an array capable of holding that number of values. In your case, you need to know the frequency of the occurrence of 'a'
s and 'A'
s for a total of 2
elements (initialized to zero).
As you execute your code and test for the occurrence of any one of the values, you simply increment the element that corresponds to that value, e.g.
a_array[0]++; /* when an 'a' is encountered */
a_array[1]++; /* when an 'A' is encountered */
After you scan the entire string, the number of 'a'
s are in a_array[0]
and the number of 'A'
s in a_array[1]
.
Putting that together, along with replacing gets
(which you NEVER, EVER USE AGAIN) with fgets
, you can do something like:
#include <stdio.h>
#include <string.h>
#define MAXC 256
int main (void) {
int a_array[2] = {0}; /* if you are counting 'a's and 'A's, you need 2 */
char buf[MAXC] = "";
while (fgets (buf, MAXC, stdin)) /* for each line of input */
{
char *p = buf;
size_t len = strlen(p); /* get the length */
if (buf[len-1] == '\n') /* remove the trailing '\n' */
buf[--len] = 0; /* by overwriting with '\0' */
for (; *p; p++) /* for each char in buf */
if (*p == 'a') /* is it an 'a'? */
a_array[0]++; /* if so increment the 'a' counter */
else if (*p == 'A') /* if it is an 'A' */
a_array[1]++; /* increment the 'A' counter */
printf ("\nthere are '%d' a's and '%d' A's in\n'%s'\n",
a_array[0], a_array[1], buf);
a_array[0] = a_array[1] = 0; /* zero for next line */
}
return 0;
}
Example Use/Output
$ printf "my dog has A lot of fleas\nA snake has none - Amen.\n" | \
./bin/num_aAs
there are '2' a's and '1' A's in
'my dog has A lot of fleas'
there are '2' a's and '2' A's in
'A snake has none - Amen.'
Now typically, you will not hardcode a_array[0]
and a_array[1]
, but will use a logical index to hold the values. For example, to calculate the frequency of each occurrence of each letter a-z
(26 characters in all), you could use:
int c_array[26] = {0};
Then when testing for each character, you simply increment c_array[*p - 'a']++;
, e.g.
while (fgets (buf, MAXC, stdin)) /* for each line of input */
{
char *p = buf;
/* trim '\n' */
for (; *p; p++) /* for each char in buf */
if ('a' <= *p && *p <= 'z')
c_array[*p - 'a']++;
...
The resulting c_array
will hold the number of 'a'
s in c_array[0]
and each corresponding letter frequency in the subsequent element through c_array[25]
which hold the frequency for all 'z'
s.
For example, if you wanted to experiment with a logical index scheme for your problem, you could use something on the order of:
for (; *p; p++) /* for each char in buf */
if (*p == 'a') /* is it an 'a'? */
a_array[*p - 'a']++; /* if so increment the 'a' counter */
else if (*p == 'A') /* if it is an 'A' */
a_array[*p - 'A' + 1]++; /* increment the 'A' counter */