字符串分割

参考:
https://blog.csdn.net/xufan0001/article/details/70187836
https://www.cnblogs.com/carsonzhu/p/5859552.html 试了第二第三方法
https://www.jb51.net/article/55954.htm 第二主要参考对象,substr函数的作用好像写错了(初始地址,字符数量)
https://blog.csdn.net/lmb1612977696/article/details/81455708 find函数找不到的使用方法

需求:类似1,3-5这种类型的数字提取

//字符串分割函数,与第一条件有关
std::vector<std::string> split(std::string str, std::string pattern)
{
 string pattern2 = "~";
 std::string::size_type pos2;
 
 std::string::size_type pos;
 std::vector<std::string> result;
 str += pattern;//扩展字符串以方便操作
 int size = str.size();
 cout << "SIZE:" << size << std::endl;
 for (int i = 0; i<size; i++)
 {
  pos = str.find(pattern, i);//第一个,出现的位置  
  if (pos<size)
  {
   std::string s = str.substr(i, pos - i);//获取字符串 

   pos2 = s.find(pattern2, 0);
   cout << "pos2:" << pos2 << std::endl;
   if (std::string::npos == pos2)
   {
    result.push_back(s);
    cout << "fuck" << std::endl;
   }
   else
   {
    std::string sf1 = s.substr(0, pos2);
    cout << "sf1:" << sf1 << std::endl;
    std::string sf2 = s.substr(pos2 + 1, s.size() - pos2);
    cout << "sf2:" << sf2 << std::endl;
    int n1 = atoi(sf1.c_str());//string转int
    int n2 = atoi(sf2.c_str());
    for (int i = n1; i< n2 + 1; i++)
    {
     std::string pi = std::to_string(i);//int转string
     result.push_back(pi);
    }
   }
   i = pos + pattern.size() - 1;
  }
 }
 return result;
}

int main()
{ 
 int num[30]{};
 std::string str;
 std::cout << "Please input str:" << std::endl;
 getline(std::cin, str);
 string pattern = ",";
 std::vector<std::string> result = split(str, pattern);
 std::cout << "The result:" << std::endl;
 for (int i = 0; i<result.size(); i++)
 {
  std::cout << "string:"<<result[i] << std::endl;
  int iResult = atoi(result[i].c_str());
  num[i] = iResult;
  std::cout << "int:" << num[i] << std::endl;
 }
  getchar();
 return 0;
}

需求:提取数字
参考:
https://zhidao.baidu.com/question/183535962.html
https://blog.csdn.net/qq_39660930/article/details/78125237

  string str = xxxx
  int result = 0;
  for (int j = 0; j <= str.size() - 1; j++)
  {
   if (str[j] >= '0'&&str[j] <= '9')//如果是数字
   {
    result *= 10;
    result += str[j] - '0';数字字符的ascii-字符'0'的ascii码就等于该数字
   }
  }
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值