求字符串中最长的单词

来源:互联网 发布:学linux 编辑:程序博客网 时间:2024/05/17 06:53

求字符串中最长的单词
描述 :
从一个给定字符串中,查找最长的单词,字符串用空格分隔不同的单词
运行时间限制 : 无限制
内存限制 : 无限制
输入 :
任意字符串,允许输入任意字符,多个单词间已空格分隔,总长度不超过128
输出 :
字符串中最长长度单词
样例输入 :
Hi world
样例输出 :
world
答案提示 :
可能存在多个同样长度的结果,如hello world,结果就是hello world。
多个相同结果间用(1个)空格分隔

struct node{    string x;    int y;};void main(){    string a;    getline(cin, a);    int loc = a.find_first_of(" ");    int max = 0;    node word[128];    int cnt = 0;    while (loc != -1)    {        word[cnt].x = a.substr(0, loc);        word[cnt].y = word[cnt].x.length();        max = max > word[cnt].y ? max : word[cnt].y;        cnt++;        a = a.substr(loc + 1);        loc = a.find_first_of(" ");    }    word[cnt].x = a.substr(0, loc);    word[cnt].y = word[cnt].x.length();    max = max > word[cnt].y ? max : word[cnt].y;    cnt++;    for (int i = 0; i < cnt; i++)    {        if (word[i].y == max)        {            cout << word[i].x << " ";        }    }}
0 0
原创粉丝点击