写一个函数,输入一行字符,将此字符串中最长的单词输出。
#include "stdafx.h"
#include "string.h"
int main(int argc, char* argv[])
{
char* strtru(char * Str, int x , int y);
char str[80], word[10];
char lword[20] = {0};
int i, j, a, b, l;
a = 0;
b = 0;
printf("请输入一行字符:\n");
gets(str);
l = strlen(str);
for(i = 0; i < l; i++)
{
while(1)
{
if(str[i] == ' ') break;
else
{
j = i;
a = i;
do
{
b = j;
j++;
}while(str[j] != ' ' && str[j] != '\0');
strcpy(word, strtru(str, a, b));
}
if(strlen(word) > strlen(lword))
strcpy(lword, word);
i = j;
break;
}
}
printf("\n");
puts(lword);
return 0;
}
char* strtru(char * Str, int x , int y) /*截取字符串Str[x]到Str[y]*/
{
int i, j;
char buf[20];
for(i = 0; i < 20; i++)
buf[i] = 0;
for(i = x, j = 0; i <= y && j < 20; i++, j++)
{
buf[j] = Str[i];
}
return buf;
}
------解决方案--------------------
#include <iostream>
#include <string> // string
#include <map> // multimap
#include <functional> // greater
#include <sstream> // istringstream
#include <cstdlib> // system("pause")
using namespace std;
typedef multimap<int, string, greater<int>>::iterator Iterator;
int main()
{
string s, buf;
multimap<int, string, greater<int>> str; // greater<int>指定按key降序排列
getline(cin, s); // 读取一行
istringstream ss(s); // 用字符流读取每个单词
while (ss >> buf) // 循环将每个单词加入multimap
{
str.insert(make_pair(buf.size(), buf));
}
Iterator beg = str.begin();
int i = beg->first; // i就是最长的单词长度
while (beg != str.end())
{
if (beg->first == i)
{
cout << beg->second << endl;
++beg;
}
else
{
break;
}
}
system("pause");
return 0;
}
输入:
it string abc buffer iter is stream
输出:
string
buffer
stream
请按任意键继续. . .