programming (20 marks)

2007-08-27 2:17 am
how can i count the number of articles appeared in sentences, using C++
for example,
I live in the kowloon, I have a sister and a brother.
number of 'the' =1
number of 'a' =2
number of 'an' =0
number of articles =3

回答 (2)

2007-08-27 4:46 am
✔ 最佳答案
You can use the string to store the whole sentence...and use space as deliminator to extract each word...finally, check if the word is an article...

You can use string.find to find the position of the space and string.substr to extract the word...

e.g.
int start = 0;
position = sentence.find('', start);
word = sentence.substr(start, position - start);
// Then it will extract "I"

2007-08-31 22:10:53 補充:
int countNoOfArticles(string sentence) {string word; int count = 0, start = 0, position = 0; while (position >= 0) {position = sentence.find(" ", start);if (position >= 0) {word = sentence.substr(start, position - start);start = position + 1;

2007-08-31 22:19:24 補充:
if (word == "a" || word == "an" || word == "the") { count ; } } }return count;}My approach is simple and clear. There is no point to convert punctuation to space.

2007-08-31 22:26:25 補充:
// Just a little bit modification, replace the checking condition byif (word == "a" || word == "A" || word == 'an" || word == "An" || word == "the" || word == "The")
2007-08-27 5:52 pm
You'd have to make a list of the articles, the size of each word, and identify the tokens. To avoid complications from punctuation marks, you can change them to spaces before . Here's one answer using strtok, and isalpha functions. If I can I will make another version that is not dependent of these functions. This program compiles under Borland C++ and runs perfectly with the given example text.
#include
#include
#include
#include
int main(int argc, char *argv[])
{
char *article[]={"the","a","an"};
int len[]={3,1,2};
int count[]={0,0,0};
char li[250];
char *ptr;
char nArt=0;
printf("Enter text:");
gets(li);
printf("%s\n",li);
// first convert the non-alpha characters to spaces
ptr=li;
while(*ptr!=0)
{
if(!isalpha(*ptr))*ptr=' ';
ptr++;
}
// TO BE CONTINUED .....

2007-08-27 09:56:17 補充:
// extract tokens (words) ptr=strtok(li," "); while(ptr!=NULL) { for(int i=0; i<3;i ) { int l1=strlen(ptr); // to be continued

2007-08-27 09:59:55 補充:
It seems to have problems with the length of text.If you send me a PM with your address, I will send you the program as an attachment.

2007-08-27 10:52:45 補充:
You can download the program using two different methods at:http://files-upload.com/files/461668/FREQ_ART.CPP


收錄日期: 2021-04-13 13:08:10
原文連結 [永久失效]:
https://hk.answers.yahoo.com/question/index?qid=20070826000051KK03260

檢視 Wayback Machine 備份