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

缺乏、安全感 2022-09-22 01:29 149阅读 0赞

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

这是一行字符串,string类型,我需要把它分割为n个数据,有的为int型,有的为double型。我这里给出我的思路:
1)找出里面有多少个逗号,并找到逗号的位置
2)通过逗号的位置,使用string中的assign函数来把局部字符串赋值为新的字符串
3)通过新的字符串转换为对应数据类型的方法来获得数据

这里给出示例代码,后方附有整个工程源码

  1. inline double StringToDouble(string s){
  2. double dblValue = atof(const_cast<const char *>(s.c_str()));
  3. return dblValue;
  4. }
  5. inline int StringToInt(string s){
  6. stringstream ss;
  7. ss<<s;
  8. int number;
  9. ss>>number;
  10. return number;
  11. }
  12. FUNCTION_STRUCT NODE_PROCESS(string s){ //用来分隔一行带有逗号的字符串,并保存在结构体里返回
  13. FUNCTION_STRUCT temp;
  14. string s_temp;
  15. int comma[11],count=0; //用comma保存逗号位置
  16. for(int i=0;i<s.length();i++){
  17. if(s[i]==','){
  18. comma[count++] = i;
  19. }
  20. }
  21. temp.SeriousDlqin2yrs = StringToInt(s_temp.assign(s,comma[0]+1,comma[1]-comma[0]-1));
  22. temp.RevolvingUtilizationOfUnsecuredLines = StringToDouble(s_temp.assign(s,comma[1]+1,comma[2]-comma[1]-1));
  23. temp.age = StringToInt(s_temp.assign(s,comma[2]+1,comma[3]-comma[2]-1));
  24. temp.NumberOfTime3059DaysPastDueNotWorse = StringToInt(s_temp.assign(s,comma[3]+1,comma[4]-comma[3]-1));
  25. temp.DebtRatio = StringToDouble(s_temp.assign(s,comma[4]+1,comma[5]-comma[4]-1));
  26. temp.MonthlyIncome = StringToDouble(s_temp.assign(s,comma[5]+1,comma[6]-comma[5]-1));
  27. temp.NumberOfOpenCreditLinesAndLoans = StringToInt(s_temp.assign(s,comma[6]+1,comma[7]-comma[6]-1));
  28. temp.NumberOfTimes90DaysLate = StringToInt(s_temp.assign(s,comma[7]+1,comma[8]-comma[7]-1));
  29. temp.NumberRealEstateLoansOrLines = StringToInt(s_temp.assign(s,comma[8]+1,comma[9]-comma[8]-1));
  30. temp.NumberOfTime6089DaysPastDueNotWorse = StringToInt(s_temp.assign(s,comma[9]+1,comma[10]-comma[9]-1));
  31. temp.NumberOfDependents = StringToInt(s_temp.assign(s,comma[10]+1,1));
  32. // 处理NA的过程
  33. if(temp.DebtRatio>1){ //如果负债率高于1,出现异常数据,此行数据剔除
  34. temp.push_backFlag = false;
  35. }
  36. else{
  37. temp.push_backFlag = true;
  38. }
  39. if(temp.NumberOfDependents<0){ //出现NA,把亲戚数置为0
  40. temp.NumberOfDependents = 0;
  41. }
  42. //验证算法完毕,没有错误
  43. return temp;
  44. }

源码地址:(之后补上)
注意,数据集必须放在d盘下才能运行

发表评论

表情:
评论列表 (有 0 条评论,149人围观)

还没有评论,来说两句吧...

相关阅读