【经典算法】:如何把一行带有分隔符的字符串分割
2016-06-26 00:10
323 查看
举个例子:数据如下
![](https://img-blog.csdn.net/20160626000155123)
这是一行字符串,string类型,我需要把它分割为n个数据,有的为int型,有的为double型。我这里给出我的思路:
1)找出里面有多少个逗号,并找到逗号的位置
2)通过逗号的位置,使用string中的assign函数来把局部字符串赋值为新的字符串
3)通过新的字符串转换为对应数据类型的方法来获得数据
这里给出示例代码,后方附有整个工程源码
源码地址:(之后补上)
注意,数据集必须放在d盘下才能运行
这是一行字符串,string类型,我需要把它分割为n个数据,有的为int型,有的为double型。我这里给出我的思路:
1)找出里面有多少个逗号,并找到逗号的位置
2)通过逗号的位置,使用string中的assign函数来把局部字符串赋值为新的字符串
3)通过新的字符串转换为对应数据类型的方法来获得数据
这里给出示例代码,后方附有整个工程源码
inline double StringToDouble(string s){ double dblValue = atof(const_cast<const char *>(s.c_str())); return dblValue; } inline int StringToInt(string s){ stringstream ss; ss<<s; int number; ss>>number; return number; } FUNCTION_STRUCT NODE_PROCESS(string s){ //用来分隔一行带有逗号的字符串,并保存在结构体里返回 FUNCTION_STRUCT temp; string s_temp; int comma[11],count=0; //用comma保存逗号位置 for(int i=0;i<s.length();i++){ if(s[i]==','){ comma[count++] = i; } } temp.SeriousDlqin2yrs = StringToInt(s_temp.assign(s,comma[0]+1,comma[1]-comma[0]-1)); temp.RevolvingUtilizationOfUnsecuredLines = StringToDouble(s_temp.assign(s,comma[1]+1,comma[2]-comma[1]-1)); temp.age = StringToInt(s_temp.assign(s,comma[2]+1,comma[3]-comma[2]-1)); temp.NumberOfTime3059DaysPastDueNotWorse = StringToInt(s_temp.assign(s,comma[3]+1,comma[4]-comma[3]-1)); temp.DebtRatio = StringToDouble(s_temp.assign(s,comma[4]+1,comma[5]-comma[4]-1)); temp.MonthlyIncome = StringToDouble(s_temp.assign(s,comma[5]+1,comma[6]-comma[5]-1)); temp.NumberOfOpenCreditLinesAndLoans = StringToInt(s_temp.assign(s,comma[6]+1,comma[7]-comma[6]-1)); temp.NumberOfTimes90DaysLate = StringToInt(s_temp.assign(s,comma[7]+1,comma[8]-comma[7]-1)); temp.NumberRealEstateLoansOrLines = StringToInt(s_temp.assign(s,comma[8]+1,comma[9]-comma[8]-1)); temp.NumberOfTime6089DaysPastDueNotWorse = StringToInt(s_temp.assign(s,comma[9]+1,comma[10]-comma[9]-1)); temp.NumberOfDependents = StringToInt(s_temp.assign(s,comma[10]+1,1)); // 处理NA的过程 if(temp.DebtRatio>1){ //如果负债率高于1,出现异常数据,此行数据剔除 temp.push_backFlag = false; } else{ temp.push_backFlag = true; } if(temp.NumberOfDependents<0){ //出现NA,把亲戚数置为0 temp.NumberOfDependents = 0; } //验证算法完毕,没有错误 return temp; }
源码地址:(之后补上)
注意,数据集必须放在d盘下才能运行
相关文章推荐
- 转:对于封装的理解
- 基于Redis实现分布式锁
- 将json形式的时间字符串转换成正常的形式
- iOS id、NSObject、id<NSObject>的区别
- 值得推荐的C/C++框架和库 (真的很强大)
- php 变量定义方法
- [学习笔记]---决策树算法(待编辑)
- ZF_20160625_Nod.LV5
- 2.4 死锁
- iOS7,iOS8和iOS9获取通讯录联系人
- MyBatis的简单例子
- iOS 归档(NSKeyedArchiver + NSCoding)
- VirtualBOX上SLES 11 SP3+Oracle 11gR2 RAC安装与部署图解
- 理解生产者消费者模型及在Python编程中的运用实例
- python结合selenium获取XX省交通违章数据的实现思路及代码
- Python实现快速排序算法及去重的快速排序的简单示例
- Python读写txt文本文件的操作方法全解析
- Python使用自带的ConfigParser模块读写ini配置文件
- Python处理JSON时的值报错及编码报错的两则解决实录
- php微信开发之批量生成带参数的二维码