题目(C++ Primer 9.39):
已知有如下string 对象:
string line1 ="We were her pride of 10 she named us: ";
string line2 ="Benjamin , Phoenix, the Prodigal ";
string line3 = "and perspicacios pacifi Suzanne";
string sentence = line1 + " " +line2 + " " + line3;
编写程序计算sentence 中有多少个单词,并指出其中最长和最最短的单词。如果有多个最长或最短的单词,则将它们全部输出。
答:
//头文件和名空间省略
void deleteComma(string & s)
{
for(string::iterator i = s.begin() ; i != s.end() ; ++i)
{
if( ispunct(*i))
{
s.erase(i);
deleteComma(s);
break;
}
}
}
void sentencehandle( const string &s)
{
stringstream ss;
ss<<s;
vector<string> svec;
string temp;
while(ss >> temp)
{
//去掉标点
deleteComma(temp);
if(temp.empty())
continue;
svec.push_back(temp);
}
string::size_type Max,Min;
Min = temp.max_size();
Max =0;
for(vector<string>::iterator i = svec.begin(); i!= svec.end() ; ++i)
{
if( (*i).size() > Max)
Max = (*i).size();
if( (*i).size() < Min)
Min = (*i).size();
}
cout<<"total words: "<<svec.size()<<endl;
cout<<"longest words: "<<endl;
for(vector<string>::iterator i = svec.begin() ; i!= svec.end() ; ++i)
{
if( (*i).size() == Max)
cout<<*i<<endl;
}
cout<<"shortest words: "<<endl;
for(vector<string>::iterator i = svec.begin() ; i!= svec.end() ; ++i)
{
if( (*i).size() == Min)
cout<<*i<<endl;
}
}
int main(int argc, char* argv[])
{
string line1 ="We were her pride of 10 she named us: ";
string line2 ="Benjamin , Phoenix, the Prodigal ";
string line3 = "and perspicacios pacifi Suzanne";
string sentence = line1 + " " +line2 + " " + line3;
cout<<endl;
sentencehandle2(sentence);
return 0;
}
============================================================================================================
上面的代码虽然已经解答了这道题,但是还是有bug
1. 若sentence 中含有" a,b " 这样的部分,则分词会错误
--------单纯以空格为标志来分词是有欠缺的,所以使用stringstream 来分词也是有欠缺的,怎么正确的分词?类似流的析取器(>>)功能?
2.寻找最长,最短单词是否还有效率更高的做法?
//待补充