not_l33t
not_l33t

Reputation: 1345

How to create a function to count occurrences of each letter?

In C, I need to create a function that, for an input, will count and display the number of times each letter occurs.

For input of "Lorem ipsum dolor sit amet", the function should return something similar to:

a: 0
b: 0
c: 0
d: 1
e: 2
f: 0
...

Upvotes: 0

Views: 1216

Answers (4)

Nico Huysamen
Nico Huysamen

Reputation: 10427

So you will basically need to read through the entire file char-by-char. Assuming that you know how file-reading works, you will need to do something like (apologies, been a while since I did C):

if (isalpha(ch)) {
  count[ch-'a']++;
}
/* rest of code where char pointer is moved on etc. */

You will need to import the ctype library for that:

#include <ctype.h>

** forgot to mention, assumed you would deduce the following: ch is your pointer to the currently read in character, while count[] is an int[], initialized to all zeros with a size of (26 * 2) = 52 to cater for both upper and lowercase. If upper and lower-case should be treated the same, you can use the tolower(int c) function also included in the ctype library. In this case you only need a 26 size array.

if (isalpha(ch)) {
  count[tolower(ch)-'a']++;
}

Then the count[] should contain the counts for each character.

/* ***** */

If you wanted to do this with only the stdio.h library, you can implement the two functions used from the ctype.h library.

A simple implementation of the isalpha(int c) function could be something like:

if (((int)c >= 'a' && (int)c <= 'z') || ((int)c >= 'A' && (int)c <= 'Z') {
  return TRUE;
} else {
  return FALSE;
}

(where TRUE and FALSE are of type your return type and something you defined).

And a REALLY simple version of tolower could be something like:

if ((int)c >= 'A' && (int)c <= 'Z') {
  return (int)c - 'a';
} else {
  return (int)c;
}

You could probably do without all the casts...

Upvotes: 5

Frankie
Frankie

Reputation: 94

Just in case you are concerned with speed:

unsigned int chars[255], *p = text;

while(*p) chars[*p]++;

for(int i = 0; i < 255; i++) if(i > ('A' - 1) && i < ('Z' + 1)) printf("%c) %u/n", i, chars[i];

Sorry for the "/n" but my mac pro does not have the right character on its keyboard...

Upvotes: 0

DennyRolling
DennyRolling

Reputation: 486

I would have an array (of the size equal to char domain) and increment the count at apropriate position.

 count[ch]++;

Upvotes: 1

Anycorn
Anycorn

Reputation: 51505

hints:

char c[26] = { 0 }; // init
// read each input chars
    ++c[input-'a'];

Upvotes: 2

Related Questions