英文:
How do I extract all the numbers in a string where the numbers are interspersed with letters?
问题
#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]);
}
}
vector<int> m_numb;
for (int i = 0; i < sum.size(); ++i){
m_numb.push_back(sum[i] - '0');
}
int sm = 0;
for (int i = 0; i < m_numb.size(); ++i){
sm += m_numb[i];
std::cout << m_numb[i] << " ";
}
std::cout << std::endl;
}
英文:
How do I loop through a string consisting of numbers and letters and add only numbers to the vector?
For example if the input is:
> e385p336J434Y26C2Z6X5Z2
I want to get a vector of int like this:
> number = {385, 336, 434, 26, 2, 6, 5, 2}
The best I got was to iterate over the line and add all the digits like that:
#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;
}
答案1
得分: 0
Output 经过处理之后是:
385 336 434 26 2 6 5 2
假设我理解你的问题和你的代码,尽管它们在显然的目标方面存在很大差异。
英文:
Foregoing the unstated reason you're not using std::isdigit
, you can/should simply build each number as you process its digits. Note that the code below does NOT check, nor care, about unsigned overflow, and makes no attempt at processing negative numbers.
#include <iostream>
#include <string>
#include <vector>
int main()
{
std::string f = "e385p336J434Y26C2Z6X5Z2";
std::vector<unsigned int> f_numb;
for (auto it = f.begin(); it != f.end();)
{
if ('0' <= *it && *it <= '9')
{
unsigned int sm = 0;
for (;it != f.end() && '0' <= *it && *it <= '9'; ++it)
sm = (sm * 10) + (*it - '0');
f_numb.emplace_back(sm);
}
else
{
++it;
}
}
for (auto x : f_numb)
std::cout << x << ' ';
std::cout << '\n';
}
Output
385 336 434 26 2 6 5 2
That, assuming I understand your question vs. your code, which differ highly in their apparent goals.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论