I recently got an assignment to input a string and count how many times each letter appears in the alphabet. First I have to set all letters to Caps, then convert all ASCII numbers to 0 through 25 (A = 0 instead of 65). Finally, I have to count how many times each letter appears. I need help on this last part because the first two are easy. I found this code pasted 9 years ago:
Code:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25 |
#define MAX_LENGTH 256
#include <stdio.h>
int main() {
char sentance[MAX_LENGTH]; // Holds the sentance
int x = 0; // Holds the current posistion for the search
int y = 0; // Holds total number of a's found
printf("Enter a sentance\n"); // Gets input
fgets(sentance, MAX_LENGTH, stdin);
while(sentance[x] != '\0') { // Loop threw sentance
if(sentance[x] == 'a') // Chech to see if the current character is a a
++y; // It is, add one to y
++x; // Update posistion
}
printf("\nThere are %i letter a's in your sentance\n", y); // Print answer
return 0;
}
// Wonder why I did c++ comments in c code when I dont do c++ |
Now this would work except I'm not allowed to use 26 If statements. Anyone have any ideas?
P.S. - One idea I have is making another array so I don't have 26 variables for each letter of the alphabet, so exampleArray[26] = 0;
But, I don't know how you would assign, say, the letter A to 1 and then If exampleArray[1] = A then (Acount++). But, this would just lead to another 26 If statements. Any help would be appreciated. Thanks.
[NOTE: This is pseudocode and I'm just giving an idea of what it would do.]