C++学习:字符串分割函数

时间:2021-05-16 19:31:45

C++实现字符串分割有多种方式,个人认为下面这种实现比较科学:

template<typename StrType>
void SplitString(const StrType& strSourceString, const StrType& strSeperator, std::vector<StrType>& vecResult)
{
StrType::size_type pos1 = 0, pos2 = strSourceString.find(strSeperator);
while (StrType::npos != pos2)
{
if (pos2 != pos1)
{
vecResult.push_back(s.substr(pos1, pos2 - pos1));
}

pos1 = pos2 + strSeperator.size();
pos2 = strSourceString.find(strSeperator, pos1);
}

if (pos1 != strSourceString.length())
{
vecResult.push_back(strSourceString.substr(pos1));
}
}

可根据需要生成std::string或std::wstring版本。