Anni_housie
Anni_housie

Reputation: 489

How to parse such C++ input string

How do I parse the following C++ string onto the following form:

string1= 2012-01     //year-month;
string2= House;      //second sub-field
string3= 20;         // integer

From the following from stdin

2012-01-23, House, 20
2013-05-30,  Word,  20    //might have optional space
2011-03-24, Hello,    25
... 
...
so on

Upvotes: 3

Views: 52

Answers (1)

user31264
user31264

Reputation: 6727

#include <vector>
#include <string>
#include <sstream>
#include <iostream>

using namespace std;
typedef vector<string> StringVec;

// Note: "1,2,3," doesn't read the last ""
void Split(StringVec& vsTokens, const string& str, char delim) {
    istringstream iss(str);
    string token;
    vsTokens.clear();
    while (getline(iss, token, delim)) {
        vsTokens.push_back(token);
    }
}

void Trim(std::string& src) {
    const char* white_spaces = " \t\n\v\f\r";
    size_t iFirst = src.find_first_not_of(white_spaces);
    if (iFirst == string::npos) {
        src.clear();
        return;
    }
    size_t iLast = src.find_last_not_of(white_spaces);
    if (iFirst == 0)
        src.resize(iLast+1);
    else
        src = src.substr(iFirst, iLast-iFirst+1);
}

void SplitTrim(StringVec& vs, const string& s) {
    Split(vs, s, ',');
    for (size_t i=0; i<vs.size(); i++)
        Trim(vs[i]);
}

main() {
    string s = "2012-01-23, House, 20 ";
    StringVec vs;
    SplitTrim(vs, s);
    for (size_t i=0; i<vs.size(); i++)
        cout << i << ' ' << '"' << vs[i] << '"' << endl;
}

Upvotes: 3

Related Questions