主要是用来处理数据的,多用于读取csv文件,比如说将123,456,789,000去除逗号变成123 456 789 000:
#include <iostream>
#include <vector>
#include <string>
using namespace std;
vector<string> split(string str, string pattern){
int pos;
vector<string> result;
str += pattern;
int size = str.size();
for (int i=0; i<size; ++i){
pos = str.find(pattern, i);
if (pos < size) {
string s = str.substr(i, pos-i);
result.push_back(s);
i = pos + pattern.size()-1;
}
}
return result;
}
int main(){
string s = "123,456,789,000";
string pattern = ",";
vector<string> strs = split(s,pattern);
for(int i = 0 ;i < strs.size();i++)
{
cout << strs[i].c_str() <<endl;
}
return 0;
}
结果:
不过如果是读取csv文件也不必要非要重新写一个split函数,因为getline函数本来就有读取到某个字符时跳过去的功能:
#include <iostream>
#include <fstream>
#include <string>
using namespace std;
const char* DATA_TRAIN_PATH = "./Dataset/Datasetc/Datac_train.csv";
const int COUNT = 10;
void get_feature() {
ifstream fin;
fin.open(DATA_TRAIN_PATH);
int i = 0 ;
while(i<COUNT){
string line;
getline(fin, line,',');
i++;
cout << line <<endl;
}
fin.close();
}
int main(){
get_feature();
return 0;
}