c++的split方法

vb,c#等语言都有字符串分割的split函数,用起来非常方便。c++的string类没有此类的函数,只好自己写一个。当然,也可以用c的系统函数strtok实现。关于strtok函数的使用见strstok详解

#include <iostream>
#include <string>
#include <vector>
#include <sstream>
#include <algorithm>
#include <iterator>
using namespace std;

void split(string in,vector<string> &vec) //以" "为分隔符
{
     istringstream ss(in);
     string t;
     while(ss>>t)
     {
                 vec.push_back(t);
     }
}
int main()
{
    string str="a b c d e f";
    vector <string> v;
    split(str,v);
    ostream_iterator<string> out (cout, "\n");
    copy (v.begin(),v.end(),out);
    system("pause");
    return 0;
}

这里用到了istringstream,将字符串转换成输入流。

首发:http://www.iwebtrados.com.cn/post/317.html

posted on 2010-02-26 22:33  网络小筑  阅读(845)  评论(0编辑  收藏  举报

导航