从一道字符串处理题目谈开去

题目(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.寻找最长,最短单词是否还有效率更高的做法?



//待补充

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值