Hey everyone,

I have a series of loops that read through a text file and then output the occurrences for each letter on the file. This seems to be fine when using small text only. When providing a lot of text it just takes too many CPU resources and that's no good for me.

Here's the code that gets the job done

for(i = 0; i < 26; i++) {
   letters[i] = 0; 
   for(j = 0; j < strlen(textStr); j++) {
       if(textStr[j] == i + 'a')
       letters[i]++;
   }
   if(letters[i] > 0)
	printf("%c - %d\n", (i + 'a'), letters[i]);
}

Some additional details:

letters[26] contains the count of occurrences. Example: {24242,2323,424,.....} where each position corresponds to a char of the alphabet.

textStr[] contains the whole text

You can assign the value returned by the function "strlen(textStr)" so you avoid calling this function strlen*26 times :)

int a = strlen(textStr);
 for(j = 0; j < a; j++) {
...
}

Maybe you should use binary files instead. This will decrease the encoding and decoding of the string that will be placed into the buffer, reducing the time your program consume dramatically.

Damn wow, such a simple fix yet so important! Thanks so much Tellalca :)

You are very welcome :)

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.