我们要检查一个字符串有多少个单词,如果我们单单去找单词来确定有多少个单词时,发现很困难,这时候可以考虑我前面给大家带来的每个单词的首字母大写这个思路出发,因为将每个单词的首字母改成大写就是检测到一个单词,这样我们就立马想到我们可以考虑单词与单词之间的分隔符号 例如: “空格”,“回车”,“:”,“,”这些符号,因为会发现每个单词都是用这些符号来分开的,这样我们思路就出来了:
1,先找到这些符号,以这些符号来分开一个个单词;
2,怎么样去确定一个单词呢,我们可以设一个字符串string sample(":,\t\n\v\r\f"),然后在我们已知的字符去找这些字符串即可;
3.最重要的就是怎么确定起点和终点,那么我可以利用find函数,在 已知字符串中查找第一个不属于 sample 的字符串的字符定为起点,而终点是第一个属于sample的字符。这样终点减去起点就是该单词的长度,然后利用while循环一次就让起点移到下一个单词开头,终点移到下一个分隔符即可,然而单词我们用assign这个函数(sentence.begin()+起始点,sentence.begin()+起始点+单词的长度)赋给单词word即可
4.然后取最长和最短,就是存一个单词就和定义的最大长度和最小长度相比即可,大的存到大的容器中,小的存到小的容器中(这里一旦出线比之前的大或小都使用clear()函数清楚前面的元素,留下该单词)
废话不多说,下面附上代码,和运行结果
#include"stdafx.h"
#include<iostream>
#include<string>
#include<vector>
using namespace std;
int main()
{
string sample(":,\t\n\v\r\f ");
string line1 = "I wanna say: We've both been pretending";
string line2 = "that we can make things the way they were before";
string line3 = "we both know that's impossible.";
size_t count=0;
vector<string>longestword,shortestword;
string word;
string sentence = line1 + ' ' + line2 + ' ' +line3;
cout<<sentence<<endl;
string::size_type startpos=0,endpos=0;
string::size_type maxlen,minlen,wordlen;
while((startpos=sentence.find_first_not_of(sample,endpos))!=string::npos)
{
count++;
endpos=sentence.find_first_of(sample,startpos);
if(endpos==string::npos)
wordlen=sentence.size()-startpos;
else
wordlen=endpos-startpos;
word.assign(sentence.begin()+startpos,sentence.begin()+startpos+wordlen);
startpos=sentence.find_first_not_of(sample,endpos);
if(count==1)
{
maxlen=minlen=wordlen;
longestword.push_back(word);
shortestword.push_back(word);
}
else
{
if(wordlen>maxlen)
{
maxlen=wordlen;
longestword.clear();
longestword.push_back(word);
}
else if(wordlen==maxlen)
{
longestword.push_back(word);
}
else if(wordlen<minlen)
{
minlen=wordlen;
shortestword.clear();
shortestword.push_back(word);
}
else if(wordlen==minlen)
{
shortestword.push_back(word);
}
}
}
cout<<"总共有:"<<count<<"个单词"<<endl;
cout<<"最长的单词为:"<<endl;
for(vector<string>::iterator it=longestword.begin();it!=longestword.end();++it)
//vector<string>::iterator iter=longestword.begin();
//while(iter!=longestword.end())
cout<<*it<<endl;
cout<<"最短的单词为:"<<endl;
for(vector<string>::iterator it1=shortestword.begin();it1!=shortestword.end();++it1)
cout<<*it1<<endl;
system("pause");
return 0;
}
这句话出自风中女王一句话,中文大概意思就是:我们都在假装可以回到从前,但我们都知道这是不可能的,我们用了那么久才敢承认。 这句话告诉我们一旦错过的,就不可能原封原样回到从前-----“珍惜”