C++的split()函数

最近写算法题经常用到字符的split()函数,这里整理一下。部分代码摘自网上。

1. 函数体如下:

 1 void _split(const string &s, char delim, vector<string> &elems) {
 2     stringstream ss(s);
 3     string item;
 4 
 5     while (getline(ss, item, delim)) {
 6         elems.push_back(item);
 7     }
 8 }
 9 vector<string> split(const string &s, char delim) {
10     vector<string> elems;
11     _split(s, delim, elems);
12     return elems;
13 }

2. 使用案例:

1 vector<string> vec = split("hello,world,c++", ',');
2 for (auto it =  vec.begin(); it !=  vec.end(); ++it) {
3         cout << *it << " ";
4 }

3.分割结果:

 1 hello world c++

 

posted on 2018-09-20 22:20  longlively  阅读(2765)  评论(0编辑  收藏  举报

导航