参考:
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码就等于该数字
}
}