如何循环遍历一个由数字和字母组成的字符串,并只向向量中添加数字?
例如,如果输入为:
电子385磅336英寸434磅26英寸26英寸52英寸
我想得到一个整型向量,如下所示:
数字= {385,336,434,26,2,6,5,2}
我得到的最好的方法是遍历该行并将所有数字相加,如下所示:
#include <bits/stdc++.h>
int main(){
string f = "e385p336J434Y26C2Z6X5Z2";
vector<int> f_numb;
string sum;
for (int i = 0; i < f.size(); ++i){
if (('0' <= f[i]) && (f[i] <= '9')){
sum += (f[i]);
}
}
//std::cout << sum << std::endl;
vector<int> m_numb;
for (int i = 0; i < sum.size(); ++i){
m_numb.push_back(sum[i] - '0');
}
int sm;
for (int i = 0; i < m_numb.size(); ++i){
sm += m_numb[i];
std::cout << m_numb[i] << " ";
}
std::cout << std::endl;
}
3条答案
按热度按时间zynd9foi1#
先不说你不使用
std::isdigit
的原因,你可以/应该简单地在处理数字时构建每个数字。注意下面的代码不会检查也不会关心无符号溢出,也不会尝试处理负数。假设我理解了你的问题和你的代码,它们在表面目标上有很大的不同。
ct2axkht2#
另一种更好地利用标准库函数的方法。https://onlinegdb.com/8eEgREuEN
我倾向于创建子步骤的函数,以便可以单独测试它们
nx7onnlm3#
这对你有用吗?