作者共发了2篇帖子。 内容转换:不转换▼
 
点击 回复
179 1
【代码】用C++标准库实现explode函数和join函数
一派护法 十九级
1楼 发表于:2016-3-22 23:35
#include <iostream>
#include <string>
#include <vector>

using namespace std;

vector<string> explode(string delimiter, string str)
{
    vector<string> arr;
    if (!str.empty()) {
        string::size_type pos, oldpos = 0;
        while (pos = str.find(delimiter, oldpos))
        {
            if (pos == string::npos)
            {
                arr.push_back(str.substr(oldpos));
                break;
            }
            else
            {
                arr.push_back(str.substr(oldpos, pos - oldpos));
                oldpos = pos + delimiter.length();
            }
        }
    }
    return arr;
}

string join(string delimiter, vector<string> &str)
{
    string result;
    vector<string>::iterator iter;
    for (iter = str.begin(); iter < str.end(); iter++)
    {
        result += *iter;
        if (iter + 1 < str.end())
            result += delimiter;
    }
    return result;
}

int main(void)
{
    vector<string> list = explode(", ", "this, that, these, those, find a pen, the pen");
    cout << "Size: " << list.size() << endl;

    vector<string>::iterator iter;
    for (iter = list.begin(); iter < list.end(); iter++)
        cout << *iter << endl;

    cout << join(";", list) << endl;

    return 0;
}
一派护法 十九级
2楼 发表于:2016-3-22 23:35
运行结果:
Size: 6
this
that
these
those
find a pen
the pen
this;that;these;those;find a pen;the pen
Press any key to continue . . .

回复帖子

内容:
用户名: 您目前是匿名发表
验证码:
(快捷键:Ctrl+Enter)
 

本帖信息

点击数:179 回复数:1
评论数: ?
作者:巨大八爪鱼
最后回复:巨大八爪鱼
最后回复时间:2016-3-22 23:35
 
©2010-2024 Arslanbar Ver2.0
除非另有声明,本站采用知识共享署名-相同方式共享 3.0 Unported许可协议进行许可。