回 帖 发 新 帖 刷新版面

主题:求大虾帮忙

找出一个英文字符串中第一个最长的英文单词,字符串中的各英文单词以一个或多个空格分隔或标点符号分隔。
如I am lucky.student went to school.
最大为student
我不会用标点把两边单词分开。。。。。。。。。求大虾帮忙

回复列表 (共1个回复)

沙发


参考:

#include <iostream>
#include <string>
#include <vector>

using namespace std;

int main(void)
{
    string puntcs(",:!.? ");
    string str(".Hello! what can II do? that is ok. now let do, something us somebodys:");
    vector<string> svec;

    string::size_type lastpos = 0;
    string::size_type firstpos = 0;
    
    vector<string> maxword;
    vector<string> minword;
    
    size_t maxlength = 0;
    size_t minlength = 0;

    while (((firstpos = str.find_first_not_of(puntcs,lastpos)) != string::npos)&&\
        ((lastpos = str.find_first_of(puntcs, firstpos)) != string::npos)) {
        
        string s(str.begin()+firstpos, str.begin()+lastpos);
        size_t size(s.size());
        if (0 == maxlength) 
            maxlength = minlength = size;
        
        svec.push_back(s);
        if (size > maxlength) {
            maxword.clear();
            maxword.push_back(s);
            maxlength = size;
        }
        else if (size == maxlength)
            maxword.push_back(s);

        if (size < minlength) {
            minword.clear();
            minword.push_back(s);
            minlength = size;
        }
        else if (size == minlength)
            minword.push_back(s);
    }
    
    cout << "Found " << svec.size() << " Words: " << endl;
    for (vector<string>::iterator it = svec.begin(); it != svec.end(); ++it) 
        cout << *it << endl;
    
    cout << "The max size is: " << maxlength << endl;
    for (vector<string>::iterator it = maxword.begin(); it != maxword.end(); ++it)
        cout << *it << endl;
    
    cout << "The min size is: " << minlength << endl;
    for (vector<string>::iterator it = minword.begin(); it != minword.end(); ++it)
        cout << *it << endl;
    
    return 0;
}



Found 14 Words: 
Hello
what
can
II
do
that
is
ok
now
let
do
something
us
somebodys
The max size is: 9
something
somebodys
The min size is: 2
II
do
is
ok
do
us
[code=c]
请填写代码
[/code][code=c]
请填写代码
[/code]

我来回复

您尚未登录,请登录后再回复。点此登录或注册