(Count occurrence of each letter in a string) Write a function that counts the occurrence of each letter in the string using the following header:
void count(const char s[], int counts[])
where counts is an array of 26 integers. counts[0], counts[1]…. and counts[25] count the occurrence of a,b,c, and z respectively. Letter are not case -sensitive. Ie. letter A and a are counted the same as a.
Write a test program that reads a string, invokes the count function and displays the non-zero counts.
Sample run of the program:
Enter a string: Welcome to New York!
c: 1 times
e: 3 times
k: 1 times
l: 1 times
m: 1 times
n: 1 times
o: 3 times
r: 1 times
t: 1 times
w: 2 times
y: 1 times
Here's the code I have so far but it stops once it gets to the 't' in 'to' and I'm not sure why and also I'm not sure how to make it not print letters that don't appear in the string. Any help would be appreciated. Thanks.
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 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43
|
#include <iostream>
#include <string>
using namespace std;
const int size = 100;
const int numberOfLetters = 26;
void count(char [], int []);
int main()
{
int counts[numberOfLetters];
char s[size];
cout << "Enter a string: ";
cin.getline(s, '\n');
count(s, counts);
for (int i = 0; i < numberOfLetters; i++)
{
cout << counts[i] << " " << static_cast<char>(i + 'a') << endl;
}
}
void count(char s[], int counts[])
{
for (int i = 0; i < numberOfLetters; i++)
{
counts[i] = 0;
}
for (int i = 0; i < size; i++)
{
{
s[i] = tolower(s[i]);
counts[s[i] - 'a'] ++;
}
}
}
|