您的位置:首页 > 其它

【经典算法】:如何把一行带有分隔符的字符串分割

2016-06-26 00:10 323 查看
举个例子:数据如下



这是一行字符串,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盘下才能运行
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: