3

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

1 Answer 1

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

2 Comments

Thanks for your code. Wonderful. I am wondering, for C++, is it usually this long when dealing with string parsing?
@Anni_housie - for simple parsing, you need to save these and several other similar functions, and use them everywhere.

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.