【问题标题】:How to parse such C++ input string如何解析这样的 C++ 输入字符串
【发布时间】:2016-11-02 04:09:26
【问题描述】:

如何解析以下 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

【问题讨论】:

    标签: c++ string parsing


    【解决方案1】:
    #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;
    }
    

    【讨论】:

    • 感谢您的代码。精彩的。我想知道,对于 C++,在处理字符串解析时通常会这么长吗?
    • @Anni_housie - 对于简单的解析,你需要保存这些和其他几个类似的函数,并在任何地方使用它们。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-10-03
    • 1970-01-01
    • 2016-05-10
    相关资源
    最近更新 更多