题目描述:对于一个字符串,输出该字符串中最长的单词。
代码:
#include<iostream>
#include<string>
using namespace std;
string MaxWord(const string str)
{
string maxstr=new char[str.length()];//存最长单词
string curstr=new char[str.length()];//记录当前单词
int max=0;
int cur=0;
maxstr[0]='\0';
for(int i=0;str[i]!='\0';++i)
{
if(isalpha(str[i]))
curstr[cur++]=str[i];
else if(cur!=0)
{
if(cur>max)
{
curstr[cur]='\0';
maxstr=curstr;
max=cur;
}
cur=0;
}
}
if(cur>max)
{
curstr[cur]='\0';
maxstr=curstr;
}
return maxstr;
}
int main()
{
cout<<MaxWord("I am a student").c_str()<<endl;;
cout<<MaxWord("hello world").c_str()<<endl;
cout<<MaxWord("different").c_str()<<endl;
cout<<MaxWord(" ").c_str()<<endl;
cout<<MaxWord("Don not lose hope").c_str()<<endl;
cout<<MaxWord("NULL").c_str()<<endl;
cout<<MaxWord("123 25 ask").c_str()<<endl;
cout<<MaxWord("563").c_str()<<endl;
cout<<MaxWord("gh* ** huji").c_str()<<endl;
cout<<MaxWord("**j %%kj").c_str()<<endl;
cout<<MaxWord("good night").c_str()<<endl;
return 0;
}
结果: