0

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

Edited by MrDiaz: forgot some details

2
Contributors
3
Replies
5
Views
6 Years
Discussion Span
Last Post by Tellalca
2

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.

0

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

This question has already been answered. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.