6 Apr 2013

c++实现split函数

收藏到CSDN网摘
python中的split函数非常好用(java,javascript,vb等语言也有提供),c++中的find,find_first_of,find_first_not_of...等函数也有其优点,但是分割字符串是个非常常见的问题,实现一个类似的函数供以后调用,会非常方便.
代码如下:
#include <iostream>
#include <string>
#include <vector>
using namespace std;

void split(vector<string> &v, string s, string delimitor=" ")
{
    size_t pos = s.find(delimitor);
    size_t last_pos = 0;
    v.clear();
    while (pos!=string::npos)
    {
        v.push_back(s.substr(last_pos,pos-last_pos));
        last_pos = pos+delimitor.size();
        pos = s.find(delimitor,last_pos);
    }
    if (last_pos<s.size()) v.push_back(s.substr(last_pos));
}

int main()
{
    string a = "aaaAAbbbAAcde";
    vector<string> v;
    split(v,a,"AA");
    for (size_t i=0;i<v.size();i++) cout << v[i] << " ";
    cout << endl;
    return 0;
}

No comments :

Post a Comment