用c++和c实现输入一串字符串,输出其中单词的个数和最长的单词,求代码

2025-01-07 14:37:55
推荐回答(1个)
回答1:

#include
#include

using namespace std;
const int MAX = 20;
int main()
{
unsigned int MaxLen = 0;
int len = 0;
int i=0;
string str[MAX];
cout << "请输入一段字符串(ctrl+z)完成输入:\n";
getline(cin,str[i],' ');

while (cin)
{

if (MaxLen < str[i].size())
{
MaxLen = str[i].size();
len = i;
}
++i;
getline(cin,str[i],' ');
}
cout << "最长字符串味:\n";
cout << "第 " << i << "个,字符长度为:" << MaxLen - 1 << " \n字符串为:"
<< str[len] << endl;
system("pause");

}

下面是使用了vector 的方法
#include
#include
#include
using namespace std;
int main()
{

vector sv;
string str;
int MaxLen = 0;
int len = 0;
cout << "请输入一段字符串(ctrl+z)完成输入:\n";
getline(cin,str,' ');

while (cin)
{

sv.push_back(str);
if (MaxLen < str.size())
{
MaxLen = str.size();
len = sv.size();
}
getline(cin,str,' ');
}
cout << "共有" << sv.size() << "个词组\n" ;
cout << "最长字符串味:\n";
cout << "第 " << len << "个,字符长度为:" << MaxLen << " \n字符串为:"
<< sv.at(len-1) << endl;
system("pause");

}