64,654
社区成员
发帖
与我相关
我的任务
分享
#include "iostream"
#include "vector"
#include "string"
#include "list"
#include "deque"
using namespace std;
/*
已知有如下 string 对象:
string line1 = "We were her pride of 10 she named us:";
string line2 = "Benjamin, Phoenix, the Prodigal"
string line3 = "and perspicacious pacific Suzanne";
string sentence = line1 + ' ' + line2 + ' ' + line3;
编写程序计算 sentence 中有多少个单词,并指出其中
最长和最短的单词。如果有多个最长或最短的单词,则
将它们全部输出。
*/
int main()
{
string line1 = "We were her pride of 10 she named us:";
string line2 = "Benjamin, Phoenix, the Prodigal" ;
string line3 = "and perspicacious pacific Suzanne";
string sentence = line1 + ' ' + line2 + ' ' + line3;
cout<<sentence<<endl;
string alpha("qwertyuioplkjhgfdsazxcvbnmQWERTYUIOPLKJHGFDSAZXCVBNM");
string alpha_not("' ';,: \t\v\r\n\f");
char kongge=' ';
string::size_type pos=0;
string temp;
string result;
vector<string> vs;
while(pos!=sentence.size())
{
if ((pos=sentence.find_first_of(alpha,pos))!=string::npos)//如果找到的是一个字母
{
temp=temp+sentence[pos];//提取单词
}
else
{//如果提取的是空格 数字 : , 等等非字母的字符 那么就把这个单词 保存到vector中
result=temp+'\0';
vs.push_back(result);
temp.clear();
}
++pos;
}
int i=0;
for (vector<string>::iterator iter=vs.begin();iter!=vs.end();++iter)
{
cout<<*iter<<" ";
++i;
if (i=5)
{
cout<<endl;
}
}
return 0;
}
while(pos!=sentence.size())
{
if (alpha.find(sentence[pos])!=string::npos)//如果找到的是一个字母
{
temp=temp+sentence[pos];//提取单词
}
else
{//如果提取的是空格 数字 : , 等等非字母的字符 那么就把这个单词 保存到vector中
//result=temp+'\0';
if(temp.size())
vs.push_back(temp);
temp.clear();
}
++pos;
}
if(temp.size())
vs.push_back(temp);
int i=0;
#include <iostream>
#include <string>
using namespace std;
void main(){
string line1 = "We were her pride of 10 she named us:";
int pos=0,begin,end;
string temp;
while(line1[pos])
{
if(line1[pos]!=' ')
{
begin=pos;
while(line1[pos]&&line1[pos]!=' ')
pos++;
pos=pos-1;//遇到空格符回退一个
end=pos;
}
while(begin<=end){
temp=temp+line1[begin];
begin++;
}
cout<<temp<<endl;
temp.clear();
pos++;
}
}