如何解析以下C ++字符串 到下面的表格:
string1= 2012-01 //year-month;
string2= House; //second sub-field
string3= 20; // integer
来自stdin
2012-01-23, House, 20
2013-05-30, Word, 20 //might have optional space
2011-03-24, Hello, 25
...
...
so on
答案 0 :(得分: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;
}