0

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?

1
  • Read the text into a string. Use a state machine to collect digits or letters. Commented May 5, 2018 at 16:23

2 Answers 2

2

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
Sign up to request clarification or add additional context in comments.

Comments

0

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:

enter image description here

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.