话不多说,直接上代码:
// 将str字符串以“division”字符分隔,最终结果生成多个子字符串并保存到vStr中。
void StringSplit(const std::string& str, std::vector& vStr, const char& division)
{
try
{
int startPos = 0;
int endPos = std::string::npos;
startPos = str.find_first_not_of(division);
while (startPos != std::string::npos)
{
endPos = str.find_first_of(division, startPos);
if (endPos != std::string::npos)
{
std::string strSplit = str.substr(startPos, (endPos - startPos));
vStr.push_back(strSplit);
}
else
{
std::string strSplit = str.substr(startPos);
vStr.push_back(strSplit);
}
startPos = str.find_first_not_of(division, endPos);
}
}
catch (const std::exception& e) {
std::cout << "parse error:" << str << std::endl;
}
}
int main()
{
std::string str = "123@456@789";
std::vector vResult;
StringSplit(str, vResult, '@');
string data1 = vResult[0];
string data2 = vResult[1];
string data2 = vResult[2];
}