一、问题描述
有一段英文由若干个单词组成,单词之间用空格分隔,编写程序提取其中所有的单词
二、问题解答
解析:这里需要用到STL在算法设计中的应用,STL在算法设计中的应用有如下几种:
⭐Ⅰ.存放主数据
Ⅱ.存放临时数据
Ⅲ.检测数据元素的唯一性
Ⅳ.数据的排序
Ⅴ.优先队列作为堆
因此这里需要用上的就是Ⅰ.存放主数据;
这里的主数据是一段英文,采用string字符串str存储,最后提取的单词采用vector容器words存储,对应的完整程序如下:
#include<iostream>
#include<string>
#include<vector>
using namespace std;
void solve(string str,vector<string>& words)
{
string w;
int i=0;
int j=str.find(" ");//查找第一个空格
while(j!=-1){//找到单词后循环
w=str.substr(i,j-i);//提取一个单词
words.push_back(w);//将单词加到words中
i=j+1;
j=str.find(" ",i);//查找下一个空格
}
if(i<str.length()-1){//处理最后一个单词
w=str.substr(i);//提取最后一个单词
words.push_back(w);
}
}
int main(){
string str="The following code computes the intersection of two arrays";
vector<string> words;
solve(str,words);
cout<<"所有的单词:"<<endl;
vector<string>::iterator it;
for(it=words.begin();it!=words.end();++it){
cout<<" "<<*it<<endl;
}
return 0;
}
执行结果:
所有的单词:
The
following
code
computes
the
intersection
of
two
arrays