Parse (split) a string in C++ using string delimiter (standard C++)

后端 未结 20 2154
时光说笑
时光说笑 2020-11-21 23:44

I am parsing a string in C++ using the following:

using namespace std;

string parsed,input=\"text to be parsed\";
stringstream input_stringstream(input);

i         


        
20条回答
  •  遥遥无期
    2020-11-22 00:05

    Function:

    std::vector WSJCppCore::split(const std::string& sWhat, const std::string& sDelim) {
        std::vector vRet;
        size_t nPos = 0;
        size_t nLen = sWhat.length();
        size_t nDelimLen = sDelim.length();
        while (nPos < nLen) {
            std::size_t nFoundPos = sWhat.find(sDelim, nPos);
            if (nFoundPos != std::string::npos) {
                std::string sToken = sWhat.substr(nPos, nFoundPos - nPos);
                vRet.push_back(sToken);
                nPos = nFoundPos + nDelimLen;
                if (nFoundPos + nDelimLen == nLen) { // last delimiter
                    vRet.push_back("");
                }
            } else {
                std::string sToken = sWhat.substr(nPos, nLen - nPos);
                vRet.push_back(sToken);
                break;
            }
        }
        return vRet;
    }
    

    Unit-tests:

    bool UnitTestSplit::run() {
    bool bTestSuccess = true;
    
        struct LTest {
            LTest(
                const std::string &sStr,
                const std::string &sDelim,
                const std::vector &vExpectedVector
            ) {
                this->sStr = sStr;
                this->sDelim = sDelim;
                this->vExpectedVector = vExpectedVector;
            };
            std::string sStr;
            std::string sDelim;
            std::vector vExpectedVector;
        };
        std::vector tests;
        tests.push_back(LTest("1 2 3 4 5", " ", {"1", "2", "3", "4", "5"}));
        tests.push_back(LTest("|1f|2п|3%^|44354|5kdasjfdre|2", "|", {"", "1f", "2п", "3%^", "44354", "5kdasjfdre", "2"}));
        tests.push_back(LTest("|1f|2п|3%^|44354|5kdasjfdre|", "|", {"", "1f", "2п", "3%^", "44354", "5kdasjfdre", ""}));
        tests.push_back(LTest("some1 => some2 => some3", "=>", {"some1 ", " some2 ", " some3"}));
        tests.push_back(LTest("some1 => some2 => some3 =>", "=>", {"some1 ", " some2 ", " some3 ", ""}));
    
        for (int i = 0; i < tests.size(); i++) {
            LTest test = tests[i];
            std::string sPrefix = "test" + std::to_string(i) + "(\"" + test.sStr + "\")";
            std::vector vSplitted = WSJCppCore::split(test.sStr, test.sDelim);
            compareN(bTestSuccess, sPrefix + ": size", vSplitted.size(), test.vExpectedVector.size());
            int nMin = std::min(vSplitted.size(), test.vExpectedVector.size());
            for (int n = 0; n < nMin; n++) {
                compareS(bTestSuccess, sPrefix + ", element: " + std::to_string(n), vSplitted[n], test.vExpectedVector[n]);
            }
        }
    
        return bTestSuccess;
    }
    

提交回复
热议问题