用C++编程!输入一行单词,求出最长的单词位置及长度!
发布网友
发布时间:2024-10-04 06:13
我来回答
共2个回答
热心网友
时间:2024-12-03 01:45
#pragma
warning(disable:4786)
#include<iostream>
#include<string>
using
namespace
std;
unsigned
int
getMaxStrPos(istream
&is,
unsigned
int
&max_len)
{
string
str;
getline(is,
str,
'\n');
cout<<str<<endl;
unsigned
int
max_pos
=
-1;
unsigned
int
len
=
0;
max_len
=
0;
cout<<str.size()<<endl;
for(int
i=0;
i<str.size();
++i)
{
if(str.at(i)
==
'
')
{
if(len
>
max_len)
{
max_len
=
len;
max_pos
=
i
-
len;
}
len
=
0;
}
else
{
++len;
}
}
if(len
>
max_len)
{
max_len
=
len;
max_pos
=
i
-
len;
}
return
max_pos;
}
int
main(int
argc,
char
*argv[])
{
unsigned
int
max_len
=
0;
cout<<"
Max_length
string
start
at
position:"<<getMaxStrPos(std::cin,
max_len)
<<
endl;
cout<<"
Max_length:"<<
max_len
<<
endl;
return
0;
}
热心网友
时间:2024-12-03 01:46
#pragma warning(disable:4786)
#include<iostream>
#include<string>
using namespace std;
unsigned int getMaxStrPos(istream &is, unsigned int &max_len)
{
string str;
getline(is, str, '\n');
cout<<str<<endl;
unsigned int max_pos = -1;
unsigned int len = 0;
max_len = 0;
cout<<str.size()<<endl;
for(int i=0; i<str.size(); ++i)
{
if(str.at(i) == ' ')
{
if(len > max_len)
{
max_len = len;
max_pos = i - len;
}
len = 0;
}
else
{
++len;
}
}
if(len > max_len)
{
max_len = len;
max_pos = i - len;
}
return max_pos;
}
int main(int argc, char *argv[])
{
unsigned int max_len = 0;
cout<<" Max_length string start at position:"<<getMaxStrPos(std::cin, max_len) << endl;
cout<<" Max_length:"<< max_len << endl;
return 0;
}