A brute force way to do this is to define a 26 element integer array named count[] and initialize all elements to 0. Now suppose all of your character data is stored in a string named data[]. Code similar to this should work:
char c;
int count[26];
int i = 0;
int index;
memset(&count, 0, sizeof(int) * 26); /* Init array to zero */
while (data[i] != null) /* Look at each character */
{
c = toupper(data[i]); /* Make it uppercase */
if (c >= 'A' && c <= 'Z') /* Is it an alpha character? */
{
index = (int) (c - 'A'); /* Make an index into the array */
count[index]++; /* Increment its count */
}
i++; /* Look at next letter */
}
While my C is rusty, this should give you an idea. For example, if the first letter in data[0] is 'd', the call to toupper() makes it 'D'. The next line checks to insure that it's a letter. The next line takes the letter D (which is ASCII code 68) and subtracts the letter 'A' (ASCII code 65) from it, which assigns 3 into index. The next statement increments that count in the array. A little thought will show:
count[0] = 'A'
count[1] = 'B'
count[2] = 'C'
count[3] = 'D'
and so on. If you work out a short sentence in the data[] array, you'll find you end up with a count of the number of occurrences of each letter.
Dr. Purdum
|