Problem
Write a sample code to find no of 'a' words in a sentence?
Eg: If a sentence is given as "I found an apple in a tree."
The output is : 1 (not 2)
We have to count no of words.
Solution
#include <iostream>
#include <iomanip>
using namespace std;
int FindNumOfA(char* sentence)
{
int cnt = 0;
if(tolower(sentence[0]) == 'a' && (sentence[1] == ' ' || sentence[1] == '\0')){
cnt ++;
}
int i = 1;
while( sentence[i] != '\0' ){
if( tolower(sentence[i]) == 'a'){
if(sentence[i - 1] == ' ' && sentence[i+1] == ' '){
cnt ++;
}
}
i++;
}
return cnt;
}
int main(int argc, char* argv[])
{
char* testCases[] = {
"I found an apple in a tree.",
"",
"a",
"A",
"A cat jumped over the table",
"A super star came to a famous site"
};
for(int i = 0; i < sizeof(testCases) /sizeof(testCases[0]); ++i){
cout << " Find " << FindNumOfA(testCases[i]) << " in " << endl;
cout << testCases[i] << endl << endl;;
}
return 0;
}
Output
Find 1 in
I found an apple in a tree.
Find 0 in
Find 1 in
a
Find 1 in
A
Find 1 in
A cat jumped over the table
Find 2 in
A super star came to a famous site
Press any key to continue . . .