İşlev:
std::vector<std::string> WSJCppCore::split(const std::string& sWhat, const std::string& sDelim) {
std::vector<std::string> 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;
}
Birim-testler:
bool UnitTestSplit::run() {
bool bTestSuccess = true;
struct LTest {
LTest(
const std::string &sStr,
const std::string &sDelim,
const std::vector<std::string> &vExpectedVector
) {
this->sStr = sStr;
this->sDelim = sDelim;
this->vExpectedVector = vExpectedVector;
};
std::string sStr;
std::string sDelim;
std::vector<std::string> vExpectedVector;
};
std::vector<LTest> 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<std::string> 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;
}
size_t last = 0; size_t next = 0; while ((next = s.find(delimiter, last)) != string::npos) { cout << s.substr(last, next-last) << endl; last = next + 1; } cout << s.substr(last) << endl;