In: Computer Science
Letter Separated Numbers (C++)
I've encountered a corrupted database that has a series of important numbers, but instead of being separated by a space, the spaces have been randomly changed in alphabetic characters. Write a function named "my_numbers" that can take a string like "18y5638b-78" and return a vector of ints {18, 5638, -78}.
Thanks!
#include<iostream>
#include<vector>
#include<string>
using namespace std;
vector<int> my_numbers(string data){
vector<int> numbers;
string temp;
// looping through string
for(int i=0;(i<data.size() && data[i]!='\0');i++){
// if digit then adding to temp
if(isdigit(data[i])){
temp += data[i];
continue;
}
// for negative sign
else if(data[i]=='-'){
if(temp.size()>=1 && temp != "-"){
numbers.push_back(stoi(temp));}
temp = "-";
}
// adding to vecror and resetting temp
else{
if(temp.size()>=1){
numbers.push_back(stoi(temp));}
temp = "";
}
}
if(temp.size()>=1)
numbers.push_back(stoi(temp));
return numbers;
}
// test function
int main(){
vector<int> numbers = my_numbers("18y5638n-78");
for(int i=0;i<numbers.size(); i++){
cout<<numbers.at(i)<<" ";
}
cout<<endl;
return 0;
}
#compile and run
$ g++ -std=c++11 filterint.cpp
$ ./a.out
18 5638 -78