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

举个例子:数据如下
这里写图片描述

这是一行字符串,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盘下才能运行

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值