正文

一道字符串操作习题 C++版块提问2009-12-06 07:19:00

【评论】 【打印】 【字体: 】 本文链接:http://blog.pfan.cn/shenjinggege/50259.html

分享到:

写过的代码还是记录下来好 题目:给定字符串,其内容为英文长句,其中包含英语单词,标点符号,空格等内容,每个英语单词使用标点符号,一个或多个空格分隔(注意!!是多个空格也可以!!).将英语长句分隔成英语单词系序列输出,并输出去单词数目.例如长句"You can count how many words this sample sentence has."的单词数目为10,其单词序列为"You" "can" "count"..... #include <iostream>using namespace std;const int MAX_NUM_OF_WORDS=50;const int MAX_LEN_OF_WORDS=30;int main(){        char sample_sentence[]="You can, count,  how    many words this sample sentence has.";        char words[MAX_NUM_OF_WORDS][MAX_LEN_OF_WORDS];    int CountWords(char* str,char words[][MAX_LEN_OF_WORDS]);    int num_of_words=CountWords(sample_sentence,words);    cout<<"\"You can, count, how    many words this sample sentence has.\""<<endl;    cout<<"There are "<<num_of_words<<" words in the sentence."<<endl;    for(int i=0;i<num_of_words;i++)        cout<<'"'<<words[i]<<'"'<<endl;    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 this sample sentence has."There are 10 words in the sentence."You""can""count""how""many""words""this""sample""sentence""has"

阅读(202) | 评论(0)


版权声明:编程爱好者网站为此博客服务提供商,如本文牵涉到版权问题,编程爱好者网站不承担相关责任,如有版权问题请直接与本文作者联系解决。谢谢!

评论

暂无评论
您需要登录后才能评论,请 登录 或者 注册