昨天有个网友问相似的问题,不过只有一个句子,稍微改了下弄成能处理多个句子的。 #include <stdio.h>const int MAX_NUM_OF_WORDS=30;const int MAX_LEN_OF_WORDS=30;int main(){ char sample_sentence[]="You can, count, how many words these sample sentences has . This is the second sentence . Third one."; char words[MAX_NUM_OF_WORDS][MAX_LEN_OF_WORDS]; int CountWords(char* str,char words[][MAX_LEN_OF_WORDS]); int num_of_sentences=0; int num_of_words; // =CountWords(sample_sentence,words); char *p_first_char=sample_sentence; int i,j,iSentence=0; puts("段落如下:"); puts(sample_sentence); putchar('\n'); for(i=0;i<sizeof(sample_sentence)-1;i++) { if(sample_sentence[i]=='.') num_of_sentences++; } printf("段落中共有%d个句子,句子如下:\n\n",num_of_sentences); for(i=0;i<sizeof(sample_sentence)-1;i++) { if(sample_sentence[i]=='.') { num_of_words=CountWords(p_first_char,words); iSentence++; printf("第%d个句子有%d个单词,单词如下:\n",iSentence,num_of_words); for(j=0;j<num_of_words;j++) printf("\"%s\" ",words[j]); printf("\n\n"); if(iSentence!=num_of_sentences) { for(j=1;sample_sentence[i+j]==' ';j++); p_first_char=&sample_sentence[i+j]; } else break; } } getchar(); return 0;}int CountWords(char *str,char words[][MAX_LEN_OF_WORDS]){ int num_of_words=0; while(true) { int num_of_chars=0; for(;*str!=' ' && *str!=',' && *str!='.';words[num_of_words][num_of_chars++]=*str++); words[num_of_words++][num_of_chars]='\0'; if(*str==',') str++; if(*str==' ') while(*++str==' '); if(*str=='.') break; } return num_of_words;}输出如下:段落如下:You can, count, how many words these sample sentences has . This is the second sentence . Third one.段落中共有3个句子,句子如下:第1个句子有10个单词,单词如下:"You" "can" "count" "how" "many" "words" "these" "sample" "sentences" "has"第2个句子有5个单词,单词如下:"This" "is" "the" "second" "sentence"第3个句子有2个单词,单词如下:"Third" "one"

评论