Reputation: 55
I have string
str="1Apple2Banana3Cat4Dog";
How to parse this string into
Apple
Banana
Cat
Dog
I used stringstream for this as below, but not worked
stringstream ss(str);
int i;
while(ss>>i)
{
ss>>s;
cout<<s<<endl;
}
the output is:
Apple2Banana3Cat4Dog
which is not the expected, any one help?
Upvotes: 0
Views: 58
Reputation: 76
You could use std::regex
for this:
#include <iostream>
#include <regex>
std::string str{"1Apple2Banana3Cat4Dog"};
int main() {
std::regex e{ "[0-9]{1}([a-zA-Z]+)" };
std::smatch m;
while (std::regex_search(str, m, e)) {
std::cout << m[1] << std::endl;
str = m.suffix().str();
}
}
Output:
Apple
Banana
Cat
Dog
Upvotes: 2
Reputation: 5166
See this snippet ( should work for fruit quantities 0-9):
#include <iostream>
#include <vector>
#include <string>
using namespace std;
int main(){
const string str = "1Apple2Banana3Cat4Dog";
vector<int> pts;
// marked integer locations
for (int i = 0; i < str.size(); i++)
{
int r = str[i] ;
if (r >= 48 && r <= 57) // ASCII of 0 = 48 and ASCII of 9 = 57
{
pts.push_back(i);
}
}
// split string
for (int i = 0; i < pts.size(); i++)
{
string st1;
if( i == pts.size()-1)
st1 = str.substr(pts[i] + 1, (pts.size() - 1) - (pts[i] + 1));
else
st1 = str.substr(pts[i]+1, (pts[i+1])-(pts[i]+1) );
cout << st1 << " ";
}
return 0;
}
Output:
Upvotes: 0