最近做一些数据方面的挖掘,发现python或perl的split函数功能,c++没有。在linux下awk很容易提取出来,但是对于偏爱vs的我来说,写一个可以提取字段的split还是很有用的,纯粹用于数据清洗。多做几个函数,以后归并为类,做成库,就方便了,总是造轮子,是没有头的。
#ifndef EXTRACT_DATA_HH
#define EXTRACT_DATA_HH
#include <iostream>
#include <string>
#include <vector>
#include <fstream>
#include <sstream>
using namespace std;
void extract_data(const string& infile,const string& outfile,vector<int> rows) //infile是输入文件的路径,outfile是输出路径,rows保存了需 要提取的列。由第一列开始计数。
{
ifstream fin;
fin.open(infile.c_str());
ofstream fout;
fout.open(outfile.c_str());
string tmp_str; //存储读取的行
while(getline(fin,tmp_str))
{
stringstream ss(tmp_str); //字符串流主要是用做分割字串
int i = 0;
string sub_str;
bool find_flag = false; //flag用于判断是否找到该字段。
while(ss >> sub_str)
{
i ++;
if(find(rows.begin(),rows.end(),i) != rows.end())
{
fout << sub_str + '\t';
find_flag = true;
}
}
if(find_flag)
{
fout << endl;
}
}
}
#endif
该方法思路简单,但缺点有二,谨慎使用
1. 只能分割空格或者TAB分割的字符串。
2.内核与用户交互过多,效率不高。
比较优秀的开源库boost已经提供了此功能,具体可以参照我的http://blog.csdn.net/zyaiwx/article/details/8491852