假设英文句子中只有 “ ”“,”“.”三种标点符号。
#include <iostream>
#include <cstring>
using namespace std;
void FindLongestWord(string &s){
int maxLength = -1;
int cnt = 0;
char word[101],longest[101];
for(int i = 0; i < s.length(); i++){
if(s[i] != ' ' && s[i] != ',' && s[i] != '.'){
word[cnt++] = s[i];
}
if(s[i] == ' ' || s[i] == ',' || s[i] == '.'){
if(maxLength < cnt){
maxLength = cnt;
for(int j = 0; j < maxLength; j++){
longest[j] = word[j];
}
}
cnt=0;
}
}
cout<<"原始字符串:\n"<<s<<endl;
cout<<"最长的单词:"<<endl;
for(int i = 0; i < maxLength; i++)
cout<<longest[i];
}
int main() {
string str;
getline(cin,str);
FindLongestWord(str);
return 0;
}
运行结果: 如有错误,欢迎指正! 2021.11.15 考研打卡
|