C++编程练习-最长单词


Description
输入一个英文句子,长度不超过200个字符。其中可包含的符号只有逗号","和句号"."。
输出句子中最长的一个单词。如果有多个这样的单词,输出最后出现的。
Input
多组数据,每行为一个句子,其中符号"."不代表句子结束,譬如人名中可含有".”。
Output
每行一个最长单词。这里单词的定义是仅由连续的字母组成的字符串。
Sample Input
Good morning.
Have a nice day.
Sample Output
morning
nice

参考代码

  1. #include <iostream>   
  2. #include <cstring>   
  3. using namespace std;  
  4. int main(){  
  5.     int max;  
  6.     char s[210],p[210];  
  7.     char *pch;  
  8.     while(std::cin.getline(s,210)){  
  9.         max = 0;  
  10.         //divided into word   
  11.         pch = strtok(s,",. ");  
  12.         while(pch != NULL){  
  13.             if(strlen(pch) >= max){  
  14.                 max = strlen(pch);  
  15.                 strcpy(p,pch);  
  16.             }  
  17.             pch = strtok(NULL,",. ");  
  18.         }  
  19.         //print result   
  20.         std::cout<<p<<std::endl;  
  21.     }  
  22.     return 0;  
  23. }  

相关内容